Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unique Class or extend Class in Python Django
In the following situation, I have a feeling I need to ?extend? the Migration class instead of re-stating it in the second module. migrations/0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [('auth', '0012_alter_user_first_name_max_length'),] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...)), ('password', models.CharField(max_length=128, ...)), ... migrations/0002_venue.py: class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [ migrations.CreateModel( name='Venue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,...)), ('name', models.CharField(blank=True, max_length=150, ...)), ('address', models.CharField(blank=True, null=True, ...)), ... Help? -
Can't get form to work for comment replies
I can't seem to get the post form to work for post replies (comments for a post). It works via the Django admin but I can't seem to display the form on the template which I think is due to my noobish backend. Layout of the "site": Front: Frontpage contains all posts which shows 3 latest comments for said posts (this part works). Posts: When you want to read a post it redirects you to another page which shows selected post (as normal) and here you can see all comments for the post (currently added directly via Django Admin). Here I want a form so the visitor can reply to the post. (This part does not work). Forms: from django import forms from django.forms import widgets, TextInput, ModelForm from .models import Comments, Post class PostForm(ModelForm): class Meta: model = Post fields = ['entry', 'post_image'] labels = { 'entry': "Post something spoopy:", } widgets = { 'entry': widgets.Textarea(attrs={'rows':10, 'cols':5}) } def __init__(self, *args, **kwargs): super(PostForm, self). __init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) class CommentForm(ModelForm): class Meta: model = Comments fields = ['comment_entry', 'comment_image'] labels = { 'comment_entry': "Answer!", } def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) for name, … -
Pythonanywhere - something went wrong - error running wsgi - modulenotfound error
I am new to django and I am doing a coursera course with little applications deployed on pythonanywhere, which has worked well so far. No I am stuck, because does not load at all. Pythonanywhere says that Something went wrong. This is the error log from pythonanywhere. Error running WSGI application ModuleNotFoundError: No module named 'django_extensions' This is my WSGI file """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() This is my settings.py file, not the entire one but the installed apps: DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'ads.apps.AdsConfig', # Extensions - installed with pip3 / requirements.txt 'django_extensions', 'crispy_forms', 'rest_framework', 'social_django', 'taggit', 'home.apps.HomeConfig', ] This is my urls.py, not the entire one, but the crucial part. import os from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url from django.contrib.auth import views as auth_views from django.views.static import serve urlpatterns = [ path('', include('home.urls')), # Change to ads.urls path('ads/', include('ads.urls')), path('admin/', admin.site.urls), … -
How to connect locally hosted Django app to Dockerized Postgres database
I'm learning Docker and after few time, I'm able to run a postgres database and a django app in two different container. The problem is that with docker, I can't use Pycharm's debugging tools. So I would like to run my code without docker but keep the database in its container. But I can't connect Dockerized postgres dabatase and locally hosted Django App. I always have this error : psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File … -
run two list same time on django template
how to run two list same time on Django-templates without using zip function. views.py l1=[1,2,3] l2=[4,5,6] return render(request,'home.html',{'l1':l1,'l2':l2}) I am passing list this type on my template page now need to run both list same time on template. how can I do this. Note---only I want do this on my template page -
How to add extra data to TextChoices?
How Can I add extra data to django.db.models.TextChoices? class Fruit(models.TextChoices): APPLE = ('myvalue', True, 'mylabel') such that: >>> Fruit.APPLE.is_tasty True >>> # And it still works otherwise >>> Fruit.APPLE.value 'myvalue' >>> Fruit.APPLE.label 'mylabel' -
Migrations in DJango
I am having DJango migrations problem while making migration following error is coming. enter image description here enter image description here enter image description here When I run my applications using python manage.py runserver it shows this :- enter image description here However running python manage.py makemigrations shows no changes detected And Above three images are result after running python manage.py migrate. what is the problem with this ? -
Nginx 502 bad gateway error when deploying django
I'm trying to set up a VPS Django server with nginx, however, I'm running into a 502 Bad Gateway error when I reload the nginx server with the following settings: sudo nano /etc/nginx/sites-available/project server { listen 80; server_name domainname.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Slide-Hackers-Web/src/static; } location /media/ { root /home/ubuntu/Slide-Hackers-Web/src/static; } location / { include proxy_params; proxy_pass https://unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock; } } I execute the commands in this order sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful sudo ln -sf /etc/nginx/sites-available/project /etc/nginx/sites-enabled sudo systemctl restart nginx sudo ufw allow 'Nginx Full' If I exclude domainname.com from the server_name, then it responds with the classic "Welcome to nginx!" page, however, if I leave it, it responds with "502 Bad Gateway nginx/1.18.0 (Ubuntu)". I'm clueless as to what I'm supposed to do, any help? P.s, gunicorn runs in the background and is active: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2021-08-17 10:38:05 UTC; 1h 58min ago Main PID: 31290 (gunicorn) Tasks: 4 (limit: 2272) Memory: 90.0M CGroup: /system.slice/gunicorn.service ├─31290 /home/ubuntu/Slide-Hackers-Web/env/bin/python /home/ubuntu/Slide-Hackers-Web/env/bin/gunicorn --access-logfile - --workers 3 … -
How do Django authorization decorators (such as: login required) work?
I am trying to better understand "behind the scenes" of the Django authorization decorators. Although I think I understand decorators in general, I find it difficult to understand the authorization decorators code. Is there any "line by line" explanation of the code (https://docs.djangoproject.com/en/2.2/_modules/django/contrib/auth/decorators/)? -
How to group results into array based on multiple similar values, Django Model
I have array as follows [ { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T06:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T05:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 0, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T16:22:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:23:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": … -
Problem updating the values of a table in django
In the bast_tag.py file I fetch the information from the site settings table which has only one row and then display it in the template. When I want to update the values in this row in the admin panel, the information is not updated, in order for the values to be updated, I have to stop the server and run the command 'py manage.py runserver' again! please guide me. Thank You base_tag.py: _site = Settings.objects.first() @register.simple_tag def title_site(): return _site.title @register.simple_tag def description_site(): return _site.description @register.simple_tag def five_icon_site(): return _site.five_icon.url @register.inclusion_tag("wooden/partials/footer.html") def footer_tag(): context = { 'about': _site.about, 'logo': _site.logo_ftr.url, } return context footer.html: <div class="d-flex justify-content-around align-items-center flex-column ftr_center wow fadeInUp"> <img src="{{logo}}"> <p class="text-center"> {{about}} </p> </div> head tag in index.html: <title>{% title_site %}</title> <meta name="description" content="{% description_site %}"> -
How to retrieve the user's url logged in with google on django
archive.html : <div class="img-description"> <img src="{{ user.urlprofile }}" class="avatar-url" alt=""> {% if user.get_full_name != '' %} <span id="helloUser-des" class="mr-2 d-none d-lg-inline text-gray-600 small">{{ user.first_name | title }}!</span> {% else %} <span id="helloUser-des" class="mr-2 d-none d-lg-inline text-gray-600 small">{{ user.username | title}}!</span>!</span> {% endif%} </div> Thank you very much in advance -
Django TestCase with Postgresql brokes PrimaryKeys
I have setted up postgresql at my django application, and after that my TestCases had broken. It always throwed ObjectDoesNotExists at any test method after first one. I have narrowed down the issue, and each time test method is called, all objects created at setUp, get their primary keys + 1. Maybe you don't understand but see my code: class ProfileTestCase(TestCase): def setUp(self): user1 = User.objects.create(username="Unit1", email="testuser1@gmail.com", password="123456") user1_profile = Profile.objects.create(user=user1, first_name='User1', last_name='User1') def test_smth0(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) def test_smth1(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) def test_smth2(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) And here is console output for this tests Why this is happening and how to fix this. Here is my connections settings to postgresql database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myapp_db', 'USER': 'admin', 'PASSWORD': 'MYPASSWORD', 'HOST': '127.0.0.1', 'PORT': '' } -
What happens when an object is created in Django admin?
I am new to Django. When we learn Python it was taught that when an object is created, the init function is initialized and all the variables that are passed are saved using self keyword. For eg: class Movie: def __init__(self,name,caption,budget): self.name = name self.caption = caption self.budget = budget obj1 = Movie('Taken',"Fight movie",250) obj2 = Movie('Wanted','Comedy movie',300) print(obj1.name) print(obj2.name) Here, in the above example when I clicked the run, two objects are initialized and saved. Hence when I print both the movies names are printed. Now when I read the documentation in Django, it says that when we create an object of a model in Django admin, it calls the save function to save the instance. Until now I was in the assumption that, the dunder init will be called just like in plain Python. The Django model looks like this: class Employee(models.Model): name=models.Charfield() dept=models.Charfield() def__str__(self): return self.name Also, here I don't see any init function explicitly defined. But when I ctrl + click on the Model, I can see a number of functions defined and there is init as well as save function defined. Now I want to know which function is called when we save any object … -
Django - Searchbar in Listview | How to define and process it
i'm totally new to django and python. I would like to add a search bar working on my Listview page as I've seen on the Django admin-site. I've seen a lot of django docs, many explainations and plenty of tutorials on the web but i have to say that I'm confused and could not find a solution for my problem. What i want to do: I have a page with a (class-based)ListView that presents 5 fields from my table. I would like to add a search bar working on 2 of these 5 fields (object id and description) as i've seen on the Django admin-site. Looking at the Docs and web these are a lot of different propositions to do that(queryset, filter, context, Q...). Personally I would like to work with the context. I tried to recover info from my searchbar but what I have implemented and tried since now is not working. Could someone help me on this matter? What is the best practice and approach? Indications on how to manage this with some code exemple? Thanks in advance! #HTML <form method="GET"> <input type="text" name="q" value="" id="searchbar" autofocus> <input class="button" type="submit" value="Search"> </form> #View class AircraftListView(ListView): model = Aircraft … -
Select related rows from different databases
There is table A (located in the default database) and table B (located in the logs database). Table B has a_id field, which contains the ID for the corresponding record from table A, which is mapped to another database. Are there any native Django ways to join the list of records from table B to the corresponding records from table A? -
how to return multiple file html in render request django?
I would like to return multiple values in multiple html files in a django view i tried that but it was a mistake def my_view(request): #bla bla bla... context ={ 'value_1':value, #.... } return render(request,{'file_1.html','file_2.html','file_2.html'},context) I have already separated it into 3 different views but the problem is that they have the same source and if I separate them I had 4 min of execution time, then the best is to combine them -
fa fa toggle icon is not changing when liked
I am building a small social media app . I made a like dislike button in django (JsonResponse). I am trying to fill the color in icon when clicked (liked) BUT it is not chaning when liked. views.py def post_like_dislike(request, user_id): post = get_object_or_404(Post, pk=user_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:all_stories') template.html <form method="GET" class="likeForm d-inline" action="{% url 'post_like_dislike' post.id %}" data-pk="{{ post.id }}"> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> <button class='likeForm' value="like" type="submit"><i class="btn fal fa-sort-up fa-6x fa-lg post-buttons "></i></button> </form> <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { // Like $('.likeForm').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: { 'submit': 'like', }, dataType: 'json', method: 'get', async: false, // Have a look into this success: function (response) { let likes = … -
How to use clear checkbox for ajax fileupload with modelform django
i am quite a noob on django and ajax so please excuse me if there is some big mistake or ugly code in my work. So I am working on an app where the user must upload different documents in a modelForm (linked to another model in 1:1). The user will probably not upload all the documents at once. I am using ajax to have a progress bar for the user. So far, the upload works fine, replacing document with another works too, but i have a problem when it comes to using the clear checkbox that django provides when a document has already been uploaded. Using submit and standard Post, the clear checkbox works fine. Using ajax it doesnt work. models.py (not posting everything since there is over 25 FileFields) class MandatVenteUpload(models.Model): mandat= models.OneToOneField('mandat_vente.MandatVente', on_delete=models.CASCADE, primary_key=True) acte_propriete = models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) carte_identite= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_amiante= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_assainissement= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_electricite= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) [...] views.py (using exception since if no document has been uploaded yet, the model does not exist) @login_required def mandat_vente_upload_view(request, num_mandat_upload): mandat_upload=get_object_or_404(MandatVente, id = num_mandat_upload) if mandat_upload.createur == request.user or request.user.is_staff: try: form_upload = MandatVenteUpload.objects.get(mandat=mandat_upload.id) form=MandatVenteUploadForm(mandat_upload, request.POST … -
Custom Authentication Still Requires Login to Admin Site
I am creating a custom user model with the ability to use a username or email to login. I have created a custom login function and can normally login into the website but it still requires me to login again when I try to access the admin site (even though the user has admin privileges). Any idea what might be the issue? User Model class User(AbstractUser): status = models.CharField(max_length=100,blank=True) class Meta: db_table='auth_user' Backend class BothAuthBackend(object): def authenticate(self, loginDetail=None, password=None): try: user = UserModel.objects.get(email=loginDetail) except: None try: user = UserModel.objects.get(username=loginDetail) except: user = None try: if user.check_password(password): return user except UserModel.DoesNotExist: return None def get_user(self, user_id): try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None View Function def login(request): if request.method == 'GET': form = LoginForm2() return render(request,'users/login.html',{'form': form}) if request.method == 'POST': form = LoginForm2(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = BothAuthBackend.authenticate(request, loginDetail=username, password=password) if user is not None: return render(request,'users/afterLogin.html') else: return render(request, 'users/login.html', {'form': LoginForm2()}) else: form = LoginForm2() return render(request,'users/login.html',{'form': form}) Settings AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend','users.backends.BothAuthBackend'] -
Configuring a django app and it's options on loading
I have a stupid yet intriguing situation in which I need to reload one of my Django Apps as the user changes some stuff in it's configuartion. To make stuff more clear for you helpers, I have made a ready function that loads some of it's components from a YAML file, then, with the help of some views, the user changes this YAML file, and long story short I want the app to reload it's self with that newly configuration options, here is some code.. # apps.py file def read_yaml(): path = os.path.join(os.getcwd(),'config.yaml') with open(path) as f: conf = yaml.safe_load(f) return conf class ActivateanduseConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'activateAndUse' def ready(self): """ A ready function to make stuff load on startup """ config = read_yaml() self.option1 = SomeClassOrFunction(config["config"]["model_ref_url"]) ================ # views.py file class SelectConfigStuff(APIView): """ API VIEW TO CHANGE Some OPtions """ def post(self, request, format=None): """ In the request we only expect the model ref name to be specified """ newlyOptzzz = request.data.get("newOpts") new_yaml_data_dict = { "option": newlyOptzzz , } with open('config.yaml','r') as yamlfile: cur_yaml = yaml.safe_load(yamlfile) cur_yaml['config'].update(new_yaml_data_dict) with open('bugs.yaml','w') as yamlfile: yaml.safe_dump(cur_yaml, yamlfile) return Response(data={"message":"done ! "}, status=201) Now the code above only changes to startup options … -
converting html code to java script string format
I am having html code for hyperlink as below: <td> <a href="{% url 'select_stock_report' book.id %}">{{ book.code }}</a></td> <td>{{book.name}}</td> it is directing to the correct page. In Script from the response I update the page as below It is not giving error (of course link page is empty because of 1 as parameter): html += "<tr> <td> <a href= '{% url 'select_stock_report' 1 %}'>"+item1.code+"</a></td>"+ "<td>" + item1.name + "</td>" + "<td>" + item1.open_qty + " </td>" But I want to replace 1 (one) with item1.id. html += "<tr><td><a href='{% url 'select_stock_report' item1.id %}'>"+item1.code+"</a></td>"+ "<td>" + item1.name + "</td>" + "<td>" + item1.open_qty + " </td>" But I am getting error. How to build the line with this replacement. I tried all "",'',+ with this item.id without success. Thanks for your help. -
Django admin TabularInLine on non-direct relation betwin model
my models : class Oeuvre(models.Model): user = models.ForeignKey(BaseUser, on_delete=models.CASCADE) title = models.CharField(max_length=255) [...] class BaseUser(AbstractUser): """User model.""" username = None email = models.EmailField(_("email address"), unique=True) [...] class UserProfile(models.Model): user = models.OneToOneField( BaseUser, primary_key=True, on_delete=models.CASCADE) [...] my admin.py class OeuvreInLine(admin.TabularInline): model = Oeuvre extra = 0 show_change_link = True this result to : tabular in line for instance of BasUser model i want the same thing but in an instance of user profile, i have already tried TabularInLine and StackInLine. thx in advence ! -
Django Model: How to only access fields related to a specific user from another model
How can i only access the addresses(Address model) of specified user(User model) from Order model. here is the code: Models.py class User(AbstractBaseUser, PermissionsMixin): phone_number = PhoneField(max_length=12, primary_key=True, unique=True) class Address(models.Model): address = models.CharField(max_length=500, blank=False,null=False,primary_key=True) customer = models.ForeignKey((User, on_delete= models.CASCADE) class Order(models.Model): order = CharField(max_length=400,blank=False,null=False) customer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address,on_delete=models.SET_NULL, null=True) the address field in Order model is my problem. When creating a new order in Django Administration, when i select one of the customers, i still can choose any address registered in database How can i limit the access to addresses to specified user. Thanks in advance -
Search list JSONField postgres Django
I have a JSONField which is an empty list ([]) by default. The data stored in the field is as follows: [{"operand":"key1","value":"value1"},{"operand":"key2","value":"value2"} and so on....] Now I want to search this JSONField and return the result if the search query is present in the values of either "operand" or "value". So for example is search query comes as "value", "value1", "key", "key2", the above mentioned record should be returned. So how to implement it in Django?