Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateSyntaxError while including javascript code in template
I am trying to follow this site to create a multi step form in my django app, from this code {% render_field form.car_make class="form-control" placeholder=form.car_make.label oninput="this.className = ''" %} i am getting the following error TemplateSyntaxError at /newcar1/ Could not parse the remainder: '"this.className = '' from '"this.className = '' I tried escaping the js thus {% render_field form.car_make class="form-control" placeholder=form.car_make.label oninput="this.className = ''"|escapejs %} but still getting the same error. Any help will be greatly appreciated. -
Django. How can I get data for an authenticated user and display it in the template?
I have subscriber and subscription models, how to display data from the Subscription model (respectively, the end_date, start_date, subscription_status fields), through the UserMembership model, for an authorized user? I need the {{subscription.end_date}}, {{subscription.start_date}} and {{subscription.subscription_status}} data for an authorized user. models.py class UserMembership(models.Model): slug = AutoSlugField(populate_from=['user', 'membership', 'created']) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") class Subscription(models.Model): slug = AutoSlugField(populate_from=['user_membership', 'created']) user_membership = models.ForeignKey( UserMembership, on_delete=models.CASCADE, verbose_name="Пользователь") subscription_status = models.CharField( choices=MEMBERSHIP_CHOICES, default='НЕ СПЛАЧЕНА', max_length=30, verbose_name="Название статуса") start_date = models.DateTimeField(auto_now=False, null=True, verbose_name="Дата начала подписки") end_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата окончания подписки") active = models.BooleanField(default=False, verbose_name="Активный") created = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") -
Receiving [Errno 111] Connect call failed ('127.0.0.1', 6379) using Django via Heroku
I'm running Django in a production environment and my websockets will connect but won't send any data. I do however receive [Errno 111] Connect call failed ('127.0.0.1', 6379) as an error. I heard that it's because of my settings.py, but so far I haven't found a solid fix. Here's what I have so far. Setup Procfile: web: daphne API.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker background -v2 settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } asgi.py: application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url('timer', TestConsumer.as_asgi()), ] ) ) ), 'channel': ChannelNameRouter({ 'background': BackgroundConsumer.as_asgi() }) }) Redis Addon for Heroku was added, but I didn't take any further steps to run it. It does however, display that its "Available" in its settings. Problem/Logs The output is a [Errno 111] Connect call failed ('127.0.0.1', 6379) error when signaling the Redis server. Websockets dont seem to do anything other than simply connect. Logs: ConnectionRefusedError at /API/1/ [Errno 111] Connect call failed ('127.0.0.1', 6379) Request Method: PUT Request URL: http://example.herokuapp.com/API/1/ Django Version: 3.2.3 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connect call failed ('127.0.0.1', 6379) Exception Location: /app/.heroku/python/lib/python3.8/asyncio/selector_events.py, line 528, … -
django.urls.exceptions.NoReverseMatch: Reverse for 'quiz' not found. 'quiz' is not a valid view function or pattern name
I am getting this error even though everything is all right. Help me debug this problem. This is my views.py file : def definition(request): return render(request, 'search/definition.html') def facts(request): return render(request, 'search/facts.html') def news(request): return render(request, 'search/news.html') This is my urls.py file : urlpatterns = [ path('', views.home, name='rios-home'), path('rios-search/', views.search_content, name='rios-search'), path('search/', views.search, name='search'), path('autosuggest/', views.autosuggest, name='autosuggest'), path('discover/', views.discover, name='discover'), path('content/', views.content, name='content'), path('about-us/', views.about_us, name='about-us'), path('definition/', views.definition, name='definition'), path('facts/', views.facts, name='facts'), path('news/', views.news, name='news'), ] And Finally this is my html file : <div class="ctg"> <a href="{% url 'definition' %}" class="ctg-option"><p>definition</p></a> <a href="{% url 'facts' %}" class="ctg-option"><p>facts</p></a> <a href="{% url 'news' %}" class="ctg-option"><p>news</p></a> </div> I had previously written quiz instead of facts but it's not written now anywhere else. So I am bewildered, why I am still getting this error -
Django Heroku: Can access file from Model, but not from media folder
I don't get how this is working. I have a django project setup on Heroku with this model: class MyModel(models.Model): csv = models.FileField(upload_to='csvs') I'm using Whitenoise for staticfiles, but nothing for MEDIA uploads. I have my MEDIA_ROOT and MEDIA_URL set in django settings in the most common way: # Settings MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' # urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The part I don't understand is about how, after I make an instance of my model through a form and upload a file, I'm able to work with the file's data when I get it from an instance of the model like so: >>> csv = MyModel.objects.first().csv >>> do_something_with_csv_file_data(csv) # How on earth is this working and it works with that csv as if it exists. However, if I go to the url myapp.herokuapp.com/media/csvs/asdf.csv I get a 404 error. It doesn't exist and I'm unable to download it like I'm able to locally on my computer (DEBUG=True on local, DEBUG=False on production of course). Again, I don't have S3 or anything setup for this project yet. If I ls in heroku bash, there is no media file, so it's understandable why I get a 404 error … -
How can I check if this instance initing from database or it is new object
I have django model of a Task. In my website Tasks can be repeated and not repeated. So I override init method in this way: def __init__(self, *args, **kwargs): """Init new Task :param period - timedelta object. How often should task be repeated :param repeated - if true task will be repeated :param end_date - datetime until which tasks will be repeated or it will be repeated for 10 years """ if not self.from_database() # I don't now how to do it if kwargs.get("repeated"): period = kwargs["period"] end_date = kwargs["end_date"] or kwargs["date_time"] + TEN_YEARS base_task = self date = base_task.date_time + period with transaction.atomic(): while date <= end_date: base_task.clone_task(date) date += period try: del kwargs["repeated"] del kwargs["period"] del kwargs["end_date"] except KeyError: pass super().__init__(*args, **kwargs) But i have problem. How can I check if this instance initing from database or it is new object. -
How long does it take for a Djoser access token until expire?
So Djoser JWT provided an access token when you login, how long until that token expires? -
how to save custom ModelForm fields in django
i have custom fields in ModelForm and there is no any values on save. im just confuse what to use in view.py to save with data form.py class AddCityForm(forms.ModelForm): duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES) country = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE) something = forms.CharField(widget=forms.TextInput(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3'})) class Meta: model = Cities exclude = ['city', 'duration', 'something'] view.py def add_city(request): data = dict() if request.method == 'POST': form = AddCityForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.city = request.POST.get('country') form.duration = request.POST.get('dur') form.something = request.POST.get('something') form = form.save() messages.success(request, f'Test for Added Successfully') data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = AddCityForm() context = dict(form=form) data['html_form'] = render_to_string('cites/modal_1.html', context, request=request) return JsonResponse(data) can any one help with this ? -
Django with Celery
How to periodically say every 24 hours delete a user who hasn't registered their email. I'm kind of confused how to start. I already pip installed it and put it in my installed_apps but what do I do now. Every tutorial I'm watching is just confusing me even more. Can anyone help? -
API views dealing with the user model is too slow (I have a custom user model)
I have this Modelviewset for my custom user model. Any API calls to this views takes a really long time that I see this thing called "(Broken Pipe)" something. It eventually does load, but my question is why is it so slow? I initially thought it might be because I use the get_user_model() function that django provides to import the model, and that function perhaps takes time. So, then I changed to the typical way of importing a model from the app itself. But even after that, any API calls are too slow. Anyone to enlighten me?? -
I can replace a '...' value to a parameter in my function's input in django-view
I'm working on a django project. In one of my views, I have a function named "glassnode". It needs a few input data, but I replace the goode ones with ... . U can see in code below: def glassnode(endpoint, ...): response = req.get( f'https://api.glassnode.com{endpoint}', { ... }, df = response.json() return df In the working version of my code endpoint fill in this way: farray2 = glassnode('/v1/metrics/market/price_usd_close', ...) But I need to enter the endpoint from the django-url. It comes to me in this way. path('charts/drawchart/v1/metrics/<str:category>/<str:detail>/', charts.views.drawchart, name='drawchart'), So I made my url in this way: def drawchart(request, category, detail): userendpoint = '/v1/metrics/'+category+'/'+detail farray1 = glassnode(userendpoint,... ) ... And it's not work! :((( the page rendered with this error: JSONDecodeError at /charts/drawchart/v1/metrics/addresses/receiving_from_exchanges_count/ -
Python. Django. An Error "No file was submitted. Check the encoding type on the form" with UpdateView class
I new with Django. I hope you could help me with this error "No file was submitted. Check the encoding type on the form". I've read several questions on stackoverflow, but there was problems with absence of "save()" in function in views.py, or absence of method "post", or absence of "csrf_token" in HTML. But I use UpdateView class and method "post" and "csrf_token" are included in HTML file. I have no any idea what the problem is. This is a blog-service with the function of adding/ updating/ deleting cities and trains. I use CreateView/ UpdateView/ DeleteView classes. Information regarding to cities and trains is stored in linked tables. All classes in the "cities" app work without problems, the same classes copied to the "trains" app don't work for creating and changing data through the form on the site. It raise an error right on the page: "Not a single file was sent. Check the encoding type of the form". At the same time, the deletion works correctly on the site. And create/ update/ delete work correctly through the admin panel. The corresponding models and forms have been created for the "trains" app. Both apps are registered in settings.py. Please tell … -
How to add watermark to video file while saving using django
I manage to add watermark, but when i save it, it saves without watermark. I need to save with watermark in media, insted of common saving video without watermark. Here is my MODEL.py class Video(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') photo = models.ImageField(upload_to='photo/%Y/%m/%d') video_uploaded = models.FileField(upload_to='video/%Y/%m/%d',blank=True,null=True) here is my view.py def add_video(request): if request.method == "POST": form = VideoUploaderForm( data=request.POST, files=request.FILES, ) if form.is_valid(): obj = form.save(commit=False) vid = request.FILES['video_uploaded'] clip = VideoFileClip(vid.temporary_file_path()) # watermark video = VideoFileClip(clip.filename) logo = (ImageClip('faiklogo.png') .set_duration(video.duration) .resize(height=50) .margin(right=8, top=8, opacity=0) .set_pos(("center", "bottom"))) final_ = CompositeVideoClip([video, logo]) final_.write_videofile('videwithwatermark.mp4') obj.save() else: form=VideoUploaderForm() return render(request, 'firstapp/add_video.html', {"foenter code hererm": form}) here is my form.py class VideoUploaderForm(forms.ModelForm): class Meta: model = Video fields = '__all__' -
Django database querysets with javascript drop down
Hello i have a FAQ model..and i have crated three FAQs.. html: <div class="accordion accordion-solid accordion-panel accordion-svg-toggle mb-10"> <!--begin::Item--> {% for i in faqs %} <div class="card p-6 header-click" id="header" data-idd="{{ i.id }}"> <!--begin::Header--> <div class="card-header"> <div class="card-title font-size-h4 text-dark"> <div class="card-label">{{ i.ques }}</div> <span class="svg-icon svg-icon-primary"> <!--begin::Svg Icon | path:assets/media/svg/icons/Navigation/Angle-double-right.svg--> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <polygon points="0 0 24 0 24 24 0 24" /> <path d="M12.2928955,6.70710318 C11.9023712,6.31657888 11.9023712,5.68341391 12.2928955,5.29288961 C12.6834198,4.90236532 13.3165848,4.90236532 13.7071091,5.29288961 L19.7071091,11.2928896 C20.085688,11.6714686 20.0989336,12.281055 19.7371564,12.675721 L14.2371564,18.675721 C13.863964,19.08284 13.2313966,19.1103429 12.8242777,18.7371505 C12.4171587,18.3639581 12.3896557,17.7313908 12.7628481,17.3242718 L17.6158645,12.0300721 L12.2928955,6.70710318 Z" fill="#000000" fill-rule="nonzero" /> <path d="M3.70710678,15.7071068 C3.31658249,16.0976311 2.68341751,16.0976311 2.29289322,15.7071068 C1.90236893,15.3165825 1.90236893,14.6834175 2.29289322,14.2928932 L8.29289322,8.29289322 C8.67147216,7.91431428 9.28105859,7.90106866 9.67572463,8.26284586 L15.6757246,13.7628459 C16.0828436,14.1360383 16.1103465,14.7686056 15.7371541,15.1757246 C15.3639617,15.5828436 14.7313944,15.6103465 14.3242754,15.2371541 L9.03007575,10.3841378 L3.70710678,15.7071068 Z" fill="#000000" fill-rule="nonzero" opacity="0.3" transform="translate(9.000003, 11.999999) rotate(-270.000000) translate(-9.000003, -11.999999)" /> </g> </svg> <!--end::Svg Icon--> </span> </div> </div> <!--end::Header--> <!--begin::Body--> <div class="hide-ans" id="{{ i.id }}" style="display: none;"> <div class="card-body pt-3 font-size-h6 font-weight-normal text-dark-50" data-id="{{ i.id }}">{{ i.ans }}</div> </div> <!--end::Body--> </div> {% endfor %} <!--end::Item--> </div> now this is showing me my three faqs which is perfect but the problem is i want them to hide the answers which i did with display =none property...and i have created a … -
keep the side dropdown menu open when i get the submenu of the main menu page
Dashboard Dashboard Manage E Money Create E Money Withdraw E Money Disburse E Money Bulk Transaction Template Report Transaction Report Transaction Pin Change Transaction Pin Profile My Profile Change Password {% if user.language == 1 %} Language: French {% else %} Language: English {% endif %} [enter image description here][1] -
Restrict roles for users management inside a Company object in Django Rest Framework
So, I have Company model like class Company(models.Model): company_name = models.CharField(max_length=150, blank=True, default='', verbose_name='Company Name') ... *other fields* And also have User model with class User(): operator_account = models.ForeignKey(Operator, on_delete=models.CASCADE, related_name='users', blank=True, null=True) Role in company = charfield with choices, can be a Manager, Regular user and Viewer ... *other fields* As you can see, in a Company I can have a multiple users with different roles. So, I need have some way to restrict users actions inside a company, base on user role and use for it serializers or viewsets. Just like if for example user has Manager role - then he will can edit company info and other users connected to company and create new users in this company and if user not Manager - he can`t create new users in company. This is a main goals, please, help! -
Trying to auto-populate a model field using JavaScript and it does not work
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, max_fractions and total_package. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now what I want is to auto-populate the max_fractions and total_package fields whenever treatment and patient_type are selected. I was suggested to use JavaScript to accomplish that. I tried and wrote the codes but to no avail. I'm trying it on max_fractions field first, when I succeed in doing that, I will do it for all the needed fields. Can anyone help me on this, it will be much appreciated. Here are my models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields='__all__' class TreatmentForm(ModelForm): class Meta: model=Treatment fields='__all__' class PatientTypeForm(ModelForm): class Meta: model=PatientType fields='__all__' class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "treatment" : forms.Select(attrs={"onmouseup":"mf();"}), "patient_type" : forms.Select(attrs={"onmouseup":"mf();"}), } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST) fm_diagnosis=DiagnosisForm(request.POST) fm_treatment=TreatmentForm(request.POST) fm_patient_type=PatientTypeForm(request.POST) if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): diagnosis=fm_diagnosis.save() treatment=fm_treatment.save() … -
Integrating a QR-code-reader based on the cozmo jsQR, a javascript QR code reading library into a DJANGO project
Am a Python newbie trying to build a PYTHON DJANGO WEB APP, am trying to implement a QR code scanner functionality on my site. I am using a jQuery plugin qrcode-reader to implement a browser interface for the cozmo jsQR QR code reading library. Firstly, OUT OF THE DJANGO PROJECT The following project structure and Code works: qr |_src | |_____beep.mp3 | |_____jquery.min.js | |_____jsQR.min.js | |_____qrcode-reader.css | |_____qrcode-reader.js | |_qrcode_reader.html Part of the qrcode-reader.js file that contains code for the $.qrCodeReader.jsQRPath and $.qrCodeReader.beepPath is as follows: var qrr, // our qrcode reader singletone instance QRCodeReader = function () {}; //******************************************************* //here are the questiobale paths $.qrCodeReader = { jsQRpath: "./jsQR.min.js", beepPath: "./beep.mp3", //******************************************************* instance: null, defaults: { // single read or multiple readings/ multiple: false, // only triggers for QRCodes matching the regexp qrcodeRegexp: /./, // play "Beep!" sound when reading qrcode successfully audioFeedback: true, // in case of multiple readings, after a successful reading, // wait for repeatTimeout milliseconds before trying for the next lookup. // Set to 0 to disable automatic re-tries: in such case user will have to // click on the webcam canvas to trigger a new reading tentative repeatTimeout: 1500, // target input element … -
Docker run at Heroku using Heroko Addon: Heroku-postgresql. Error: could not translate host name "db" to address: Name or service not known
I am using docker and attempting to set up a webapp at heroku via git and set up docker container at heroku as a postgresql database via Heroku addon: heroku-posgresql and the error is generated message as "django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known". It is my first time using heroku-postgresql. What it did went wrong? heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn config.wsgi $ heroku create $ heroku stack:set container -a peaceful-eyrie-17232 $ heroku addons:create heroku-postgresql:hobby-dev -a peaceful-eyrie-17232 $ heroku git:remote -a $ git push heroku master $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ peaceful-eyrie-17232... up, run.9164 (Free) Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known The … -
Serializing (to json) a dictionary containing a Django queryset which contains DecimalField items
I have a Django queryset containing model objects with some fields being Decimal objects, a format that doesn't exist in json. I know how to use Django serializers to convert this queryset to json. However, I need to wrap the queryset in a dictionary before sending it to the front-end, like so: { "type": stream1", "data": queryset } Serializers don't work here. Error is "AttributeError: 'str' object has no attribute '_meta'". I understand why this is the case. What I've tried (nested json objects): I serialized the queryset and then added it to the dictionary before converting the dictionary to json. But this is inelegant since it requires the front-end to parse the dictionary first, and then parse the serialized value inside it. Makes for a poor experience. How do I serialize the dictionary containing the Django queryset in one shot? -
How to use csrf-token in POST-hyperlink?
I need to make a hyperlink in Django for a POST-request. For example, "Add to blacklist" in the menu. It's easy to do with a form with a submit button but I need a menu item not button. I found Javascript code for doing this but it gives me an error 403: CSRF token missing or incorrect. And I couldn't find understable for me information how to insert csrf-token into the Javascript function. I don't know Javascript, I write in Python. Here's the function from https://ru.stackoverflow.com/questions/65237/Вызов-метода-post-через-ссылку: <script type="text/javascript"> function postToUrl(path, params, method) { method = method || "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); form.submit(); } </script> Here's how I call it: <a href="#" onclick="postToUrl('/account/add_to_blacklist/watched_user_id{{ message.recipient.user.id }}/next={{ request.get_full_path }}', {}, 'POST');">To blacklist</a> This is my view: class AddToBlacklistView(View): def post(self, request, watched_user_id, next_url=None, *args, **kwargs): if not next_url: next_url = '../profile.html/user_id{0}'.format(watched_user_id) if request.user.is_authenticated: try: user = User.objects.select_related("profile").get(username=request.user) watched_user = User.objects.select_related("profile").get(id=watched_user_id) except User.DoesNotExist: raise Http404 if watched_user.id == user.id: return redirect(next_url) if watched_user not in user.profile.blacklist.all(): user.profile.blacklist.add(watched_user) user.save() if watched_user.profile in user.profile.friends.all(): user.profile.friends.remove(watched_user.profile) if user.profile in watched_user.profile.friends.all(): friendship = Friendship.objects.get(user=watched_user.profile, friend=user.profile) … -
Django 'Dynamic' object storing in mongoDB
Is it possible to detect dynamically what object 'user' is sending based on its property/properties/type and after that store it into table ? I have abstract base class ConditionModel and a Concrete class Strategy which contains lists of ConditionModels. There will be many different condition model classes that will inheritance from Condition base class. Those classes will have different fields inside but still should implement the base class property and overwrite Isfulfilled method. How to create my djongo model that will accept this "dynamic different fields" ? My code: I have created abstract objects in models.py: class AbstractModelMeta(ABCMeta, type(models.Model)): pass The condition model which has only one field and one method to overwrite by child class: class ConditionModel(models.Model, metaclass=AbstractModelMeta): type = models.CharField(max_length=50) class Meta: abstract = True def __init__(self, type: str): self.type = type @abstractmethod def Isfulfilled(self) -> bool: pass And there's strategy model that will have list of Conditions type classes: class Strategy(models.Model): name = models.CharField(max_length=50) conditions = models.EmbeddedField(model_container=ConditionModel) def someMethods ( ... ) Here's an example of not abstract condition class: class SomeCondition(ConditionModel): type = models.CharField(max_length=50, default="Price") field1 = models.DecimalField(max_digits=1000, decimal_places=5) field2 = models.DecimalField(max_digits=1000, decimal_places=5) ( some other fields ) def Isfulfilled(self) -> bool: return field1 < field2 … -
what does value error in django refers , i am stuck
#ValueError: "<Profile: Profile object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. what is value error why am i getting these , ValueError at /admin/profiles/profile/add/ "<Profile: Profile object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify # Create your models here. from . utils import get_random_code class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(default="no bio...", max_length=300) email = models.EmailField(max_length=200, blank=True) country = models.CharField(max_length=200, blank=True) avatar = models.ImageField(default='avatar.png', upload_to='avatars/') friends = models.ManyToManyField(User, blank=True, related_name='friends') slug = models.SlugField(unique=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def save(self, *args ,**kwargs): ex = False if self.first_name and self.last_name: to_slug =slugify(str(self.first_name ) + "" + str(self.last_name)) ex = Profile.objects.filter(slug =to_slug).exists() while ex: to_slug = slugify(to_slug+""+str(get_random_code())) ex = Profile.objects.filter(slug=to_slug).exists() else: to_slug = str(self.user) self.slug=to_slug super().save(*args ,**kwargs) #`enter code here`utlis.py file import uuid def get_random_code(): code = str(uuid.uuid4())[:8].replace('-', '').lower() return code -
Get Django objects JSONField that contains any item of list in its specific value
I have a JSONField in Django model like this: #Object1 JSONField: {"Fruits": ["banana", "cherry", "apple", "strawberry"], "Vegetables": ["broccoli", "cucumber", "eggplant"]} #Object2 JSONField: {"Fruits": ["fig", "coconut", "pear"], "Vegetables": ["broccoli", "cucumber", "eggplant"]} When I only search one item in objects it return the result correctly: def get_queryset(self, *args, **kwargs): qs = super(RecommendsListView, self).get_queryset(*args, **kwargs) qs = qs.filter(data__Fruit__icontains='cherry') # This return Object1 currectly but the problem is where I want to get those objects that their Fruits value have at least one of the items of the list: def get_queryset(self, *args, **kwargs): qs = super(RecommendsListView, self).get_queryset(*args, **kwargs) lst = ['cherry', 'coconut'] qs = qs.filter(data__Fruit__icontains=lst) # This return Object1 currectly I expect this to return both object1 and object2, but it does not return anything. -
How to not set image field as null when PUT/Patch in Django rest framework
I have a website that has users each user has his own profile, the problem is when the user wants for example edit his email or username and save this appear profile_image: The submitted data was not a file. Check the encoding type on the form. I thought that the frontend problem and I tried to edit the user username field without touch the image field in the Django rest framework API screen but it shows the same problem the user image field has a path to his image in getting but in put the image input is empty, how I can get edit the user other fields without loss the user image my view class UserProfileRetrieveUpdate(generics.GenericAPIView): serializer_class = UserProfileChangeSerializer def get(self, request, *args, **kwargs): serializer = UserProfileChangeSerializer( instance=request.user) return Response(serializer.data) def put(self, request, *args, **kwargs): user_profile_serializer = UserProfileChangeSerializer( instance=request.user, data=request.data, ) if user_profile_serializer.is_valid(): user_profile_serializer.save() print(user_profile_serializer.data) return Response(user_profile_serializer.data, status=status.HTTP_200_OK) errors = dict() errors.update(user_profile_serializer.errors) return Response(errors, status=status.HTTP_400_BAD_REQUEST) My serializer class UserProfileChangeSerializer(serializers.ModelSerializer): profile_image = serializers.ImageField() class Meta: model = Account fields = ('pk', 'email', 'username', 'UserFullName', 'bio', 'profile_image')