Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting dictionary in django model using json field
I am trying to store a dictionary in my Django project as a model. The model is present but it wont update the values. any ideas? model.py: class MyModel(models.Model): jsonM = JSONField() Main.py: myList = [1,2,3,4,5,6,7,8,9] print("this is my model") MyModel.objects.all().update(jsonM=myList) When i do: print(MyModel.objects.all()) print(type(MyModel.objects.all())) I get the following: <QuerySet []> <class 'django.db.models.query.QuerySet'> -
How to decrease the lenght of the token in django_rest_passwordreset
settings.py Putting these does not work, it keeps on sending 50 digit code,Do i have to put somthing in this code, please help "CLASS": "django_rest_passwordreset.tokens.RandomNumberTokenGenerator", "OPTIONS": { "min_number": 4, "max_number": 5, } }``` ### models.py ### Do i have to put somthing in this code, please help ```@receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): email_plaintext_message ="Your-One-Time-OTP is {}".format(reset_password_token.key) # "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) send_mail( # title: "Password Reset for {title}".format(title="Tag On Account"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) }``` -
Django - how to manage variables inside a translation block?
I have the following paragraph at my django template I want to translate: <p>Hello and welcome to {{ settings.SITE_NAME }}, nice to meet you</p> How can I process the SITE_NAME variable at my .po file? -
Uncaught TypeError: $.ajax is not a function | Updating dropdowns based on Django model
I have a problem when trying to update my dropdown (<select> element) based on Django model triggered by another dropdown (let's call it A) change. I followed this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html When I change the dropdown A, I get the following error: Uncaught TypeError: $.ajax is not a function Based on similar questions I made sure that I include this line before my script: <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> and I'm not using the slim version of jquery. Here is the part of my HTML code of my dropdown A and JS that is responsible for updating the second dropdown. <select id="my-selection" dropdown-data-url="{% url 'ajax_get_data' %}"> <option value="1">First Option</option> <option value="2">Second Option</option> </select> <script> $(document).ready(function() { $("#my-selection").change(function () { var url = $("#my-selection").attr("dropdown-data-url"); // get the url of the proper view var my_selection = $(this).val(); // get the selected input from dropdown $.ajax({ url: url, data: { 'selection': my_selection // add selected option to the GET parameters }, success: function (data) { $("#second-dropdown-selection").html(data); } }); }); }); </script> I will be grateful for any suggestions. -
How to sync postgres database with neo4j in realtime while using Django-admin?
So currently I am working on a Django project where I have two different databases. one is PostgreSQL and the second is Neo4j. what I want is real-time sync between both databases. I am using the Django-admin panel for crud operation in the Postgres database. now I want every crud operation update in the neo4j database also. but I don't know how to do it. -
How to access foreign key of child table in Django views and if there is no relation than store 0 in foreign key
1] I want access foreign key of child table how to access it inside view for example in models.py class Test(models.Model): answer = models.ForeignKey(Answers,on_delete=models.PROTECT) class Answers(models.Model): chapter_name = models.ForeignKey(Chapter,on_delete=models.PROTECT) class Chapter(models.Model): lesson_name = models.CharField(max_length=200) in my views.py def test(request): test_data = Test() chapter_name = #How to access chapter name 2] How to store 0 if user selects other option in form if user selects test-1 than id will be 1 or any number but if user will select other option than it should store 0 in foreign key field how to do that -
djnago-admine startproject pyshop doen't work whith me
django-admin : Le terme «django-admin» n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable. Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez. Au caractère Ligne:1 : 1 django-admin startproject pyshop everytime i use djnago-admin startproject i get this msg -
Django: complex order by query with nested models
I have following 3 models from django.db.models import Max from django.utils import timezone class Product(models.Model): name = models.CharField( blank=False, max_length=256 ) class TaskGroup(models.Model): name = models.CharField( blank=False, max_length=256 ) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=False, blank=True ) class Task(models.Model): name = models.CharField( blank=False, max_length=256 ) task_group = models.ForeignKey( TaskGroup, on_delete=models.CASCADE, null=False, blank=True ) execute_at = models.DateField( blank=True null=True, ) I can order the products by Task execute_at date. Products.objects.annotate( last_task=Max('taskgroup__task__execute_at') ).order_by('-last_task') However, I need to consider only the first date that is greater than today i.e I need something like Products.objects.annotate( last_task=('taskgroup__task__execute_at' >= timezone.now()).first() ).order_by('last_task') How can I do this? It would be nice to do it in a single query. -
How do i integrate Django - Tenant with Django Haystack
I'm currently using Django-tenant package that provides the Multi-Tenancy based on different Schemas, I'm also using django-haystack with ElasticSearch in BackEnd for Searching, I need some help to figure how to index records for different schemas with ElasticSearch, what approach should I follow, and is it even possible by using django-haystack. -
hi i am avik , i am working with some django project but i am facing problems in uploading files to a particular directory, i am stuck with it
i am using a html template to upload a file but i don't know how to process that file in django views file i also have a model which is connected with the database here is my html file {% extends 'base.html' %} {% block body %} <form action="file" method="post" enctype="multipart/form-data" > {% csrf_token %} <input type="text" name="userName" placeholder="username"> <input name="file" type="file"> <input type="submit" value="submit"> </form> {% for message in messages %} {{ message }} {%endfor%} {% endblock %} and here is my views.py function def File(request): if request.user.is_authenticated: if request.method == 'POST': user = request.POST['userName'] file = request.FILES print(file) # file = request.POST.copy() # file.update(request.FILES) # content_type = copied_data['file'].get('content-type') # path = os.path.join(r'C:\Users\harsh\PycharmProjects\swatchBharat\SwatchBharat\media\files\\',file) if User.objects.filter(username=user).exists(): file2 = points() file_obj1 = DjangoFile(open(file, mode='rb'), name=file) file_obj = File.objects.create(title=file, file=file_obj1, content_object=file, author=file.client) file2.file =file2.save(ContentFile(file_obj)) file2.user = user file2.save() return HttpResponse('sucess bale bale!!!!!!!') else: messages.info(request,'the username you entered is incorrect') return redirect("file") return render(request, 'file.html') else: return HttpResponse('sorry this is restricted, login to continue') my model.py file from django.db import models # Create your models here. class points(models.Model): user = models.TextField(max_length=50,default=None) file = models.FileField(upload_to='files/') point_3 = models.BooleanField(default=False) point_5 = models.BooleanField(default=False) point_9 = models.BooleanField(default=False) i am stuck with it pls someone help me out -
How to get the db id/pk of the returned querysets?
I have a model query that returns the max value for each day in the database, but it only returns the date and the count. I'm in need of the id/pk in the database, but i'm not sure how to gather it. from django.db import connection from datetime import datetime, timedelta, date def query(request): test = NetworkStats.objects.extra(select={'day': connection.ops.date_trunc_sql( 'day', 'date')}).values('day').annotate(online=Max('online')) for obj in test: print(obj) The above code prints out the following: {'day': datetime.datetime(2021, 4, 22, 0, 0, tzinfo=), 'online': 485} {'day': datetime.datetime(2021, 4, 23, 0, 0, tzinfo=), 'online': 466} But I specifically need the id/pk of these values returned. How can I achieve this? -
line 20, in init eng = _activeEngines[driverName]
--I'm doing a voice assistant in python but when I run the program, this wrong appears --this is my code, I have pyttsx3 and pyaudio import pyttsx3 engine = pyttsx3.init() engine.setProperty("rate", 150) text ="Hola a todos" engine.say(text) -
Typeahead returning object count instead of selectable strings in Django
I am trying to implement typeahead.js for my application. I followed through with some of the following examples stackoverflow and Twitter typeahead official doc. I created a Django Rest API which works perfectly well, I have also been able to get the typeahead to pop up suggestions. After all these, I am faced with two difficulties that I have been unable to resolve on my own. The first is that instead of showing string results, the script is returning total object count , while the second problem is that the pop-up suggestion is not selectable. Is there a way to solve these issues? main.js //live search $(document).ready(function(){ var recruitmentLeadsSearchResults = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('lead'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '../auth/api/data/', remote: { url: "/auth/api/data/", wildcard: '%QUERY', } }); $('.typeahead').typeahead(null, { name: 'leads-display', display: 'lead', source: recruitmentLeadsSearchResults, templates: { empty: [ '<div class="empty-message">', 'No user found', '</div>' ].join('\n'), suggestion: function(data){ return '<div class="live-search-results">' + '<strong>' + data + '</strong>' + '</div>'; } } } ); }); views.py @require_http_methods(['GET']) def search_team_lead_ajax(request): lead = request.GET.get('lead') data = {} if lead: leads = Board.objects.filter(lead__first_name__icontains=lead) data = [{'lead': lead} for lead in leads] return JsonResponse(data, safe=False) -
Django Rest Framework using custom mixin with ApiView not working
I have a Class Based View that inherits from ApiView with a get and post function. I wrote a custom mixin to add the functionality for the post request to accept both a list of objects and also a single object. When I make the class inherit the mixin nothing happens class CreateListModelMixin: def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) class User_ListView(APIView, CreateListModelMixin): permission_classes = [DjangoCustomModelPermissions] queryset = User.objects.none() # TO define a dummy queryset for the purpose of the above permission class def get(self): db_data = User.objects.all().prefetch_related("installation_mast") serializer = User_Serializer(db_data, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = User_Serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The get_serializer method of the mixin is not being called. Any help will be appreciated -
react js axios not showing images from django rest api
i have build the api and fetching. all the data are stored in database ,everything except image is showing and fetching but images are not. pls see the code models class Category2_products(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) image = models.ImageField(upload_to='products') description = models.TextField() delivery = models.CharField(max_length=30) key_point1 = models.CharField(max_length=70,blank=True) key_point2 = models.CharField(max_length=70,blank=True) key_point3 = models.CharField(max_length=70,blank=True) key_point4 = models.CharField(max_length=70,blank=True) key_point5 = models.CharField(max_length=70,blank=True) key_point6 = models.CharField(max_length=70,blank=True) key_point7 = models.CharField(max_length=70,blank=True) key_point8 = models.CharField(max_length=70,blank=True) key_point9 = models.CharField(max_length=70,blank=True) def __str__(self): return f'{self.name}' serializers class Category1_Api(serializers.ModelSerializer): class Meta: model = Category1_products fields = '__all__' views.py class Category1_data(APIView): def get(self,request): model_data = Category1_products.objects.all() serializers = Category1_Api(model_data, many=True) return Response(serializers.data) Cat1.js function Cat1() { const [Cat1,setCat1] = useState([]) useEffect(() => { axios.get('http://127.0.0.1:8000/category/1/api').then(e => { console.log(e.data) setCat1(e.data) }) }, []) const Cat1_map = Cat1.map(e => { return( <div> <div className="object_cat1"> <img src={e.image.urls} alt="" id='cat1_product_img'/> <div className="cat1_text"> <p className="cat1_product_name">{e.name}</p> <Link id='cat1_product_link'>View</Link> </div> </div> </div> ) }) i hope you can help me -
Deferred Model Pattern
My Django-SHOP Website sells Videos so my Videomodel has a deferred foreign key to django-filer, like so: class VideoFile(with_metaclass(deferred.PolymorphicForeignKeyBuilder, models.Model)): file = FilerFileField( on_delete=models.CASCADE ) video = deferred.OneToOneField( Product, on_delete=models.DO_NOTHING ) class Video(AvailableProductMixin, Product): videofile = models.ManyToManyField( 'filer.File', through=VideoFile, verbose_name=_("Video file") ) If I use 'Product' in the VideoFile class it gives me the following error: django.core.exceptions.ImproperlyConfigured: Deferred foreign key 'VideoFile.video' has not been mapped but if I use 'BaseProduct' I get this error: ERRORS: project.VideoFile: (fields.E336) The model is used as an intermediate model by 'project.Video.videofile', but it does not have a foreign key to 'Video' or 'File'. The documentation does not really help me, so does anyone know what the problem is here? -
Why Django does not store relations in a database
An empty Django 3.2 project, and only this content in the model.py file and django admin enabled: from django.db import models class Tag(models.Model): name = models.CharField(max_length=150, verbose_name="Tag Name") def __str__(self): return '{}'.format(self.name) class Post(models.Model): name = models.CharField(max_length=150, verbose_name="Post Name") tags = models.ManyToManyField(Tag, blank=True, related_name='posts') def __str__(self): return '{}'.format(self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) tags = ['a','b','c','d','e'] for tag in tags: dbtag, created = Tag.objects.get_or_create(name=tag) self.tags.add(dbtag) super().save(*args, **kwargs) print (self.tags.all()) Problem: The code creates tags and saves it to the database. The code creates relations, because print -command prints: <QuerySet [<Tag: a>, <Tag: b>, <Tag: c>, <Tag: d>, <Tag: e>]> But relations does not store it in the database, Why? Am I doing something wrong? -
Django sitemaps causes runtime error on random model
I'm trying to add sitemaps to my Django website using its builtin framework django-sitemaps. I believe I have set up everything correctly according to the (at times hard to follow) documentation, but now when I try to runserver I get the following error: [...snip...] File "E:\Programming\my_project\my_project\urls.py", line 7, in <module> from sitemaps import StaticViewsSitemap File "E:\Programming\my_project\some_app\sitemaps.py", line 2, in <module> from models import Story File "E:\Programming\my_project\some_app\models.py", line 18, in <module> class Category(models.Model): File "E:\Programming\my_project\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class models.Category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The model in question is part of some_app which most definitely is in INSTALLED_APPS, it has worked for months, I haven't touched it in the slightest, and if I comment out everything that relates to sitemaps it works perfectly as it has until now. The model is simply the first one declared in models.py. I think the error has to do with imports and the right parts of the project not being initialised when the sitemaps are constructed. Here is the project's directory tree with the relevant files: my_project ├ my_project │ ├ ... │ ├ urls.py │ └ sitemaps.py ├ some_app │ ├ … -
How to set success url as the previous page after updating an instance in django
I am trying to redirect the user to the previous page after they have updated an instance in the Model Class. So, here is the view for the update: class ClassStatusDetailView(OrganisorAndLoginRequiredMixin, generic.UpdateView): model = Class template_name = "agents/class_status_detail.html" context_object_name = "class" fields = ['status'] def get_success_url(self): return reverse("agents:agent-list") Right now, as you can see, the get_success_url is set to "agents:agent-list", which is not the previous page. Also, here is the template for the update view in case you need it: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <a class="hover:text-blue-500" href="#">Something</a> <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800">{{ class.student }}</h1> </div> <form method="post" class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md"> Update </button> </form> </div> {% endblock content %} However, there is a catch. The previous page I want to return to is a function view with a primary key. So, not only do I have to go back to this function view, but I also have to go to the correct primary key. Please tell me if you guys need any other information. Thank you! -
django-elasticsearch-dsl: how to search across multiple documents?
I have several ElasticSearch documents in Django describing each a different type of object: 'MovieDoc,' 'CartoonDoc,' etc. For now on, I can search across every such document individually: document = MovieDoc results = document.search().query('some phrase') But what if I want to search across all documents at once and get the results altogether sorted by relevance (i.e. not searching every individual document and merging thereafter)? I have tried something like this based on the documentation of elasticsearch-dsl, but this did not yield any results: from elasticsearch_dsl import Search results = Search(index=['movie_docs', 'cartoon_docs']).query('some phrase') -
how to create an API for registering tenants in django-tenant?
I'm using django-tenants with a decoupled front end. Everything works for per-tenant apps, but I struggle to figure out to make an api for registering of tenants (and anything else from django-tenants). Obviously I'm lost about serializers,too. For per-tenant user registration, I extend BaseUserManager from django.contrib.auth.base_user. This UserManager handles creating users. So, I would expect that django-tenant would have something like TenantManager, but django-tenant docs don't have documentation on that and I can't find it in code. What django-tenants does have is custom user commands like create_tenant and create_tenant_superuser, which could be useful since in django you can access any management command like this: from django.core.management import call_command call_command('my_command', 'foo', bar='baz') But django-tenants does not have the docs on that either. It seems to me that they're defined here but the code is too complex for me, i don't know how to extent it in my app. -
why does it urlpatterns give me page error?
I have the following in my urls: urlpatterns = [ path('admin/', admin.site.urls), # path('login/', views.login_user), # path('login/submit', views.submit_login), # path('logout/', views.logout_user), # path('', RedirectView.as_view(url='index/all')), path('', views.index), path('index/all/', views.listar_all), path('index/salgados/', views.listar_salgados), path('index/esfirras/', views.listar_esfirras), path('index/pizzas/', views.listar_pizzas), path('index', views.submit), path('submit/', views.submit), path('index/all/submit/', views.submit), ] I have the following in my view: def index(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_all(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(active=True) # return render(request, 'index/', {"salgados":salgados}) return render(request, 'index.html', {"salgados":salgados}) def listar_salgados(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Salgados',active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_esfirras(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Esfirras',active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_pizzas(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Pizzas',active=True) return render(request, 'index.html', {"salgados":salgados}) @csrf_protect def submit(request): print(request.POST) if request.POST: # return render(request, 'submit.html', {"salgados":salgados}) # return render(request, '/submit/', {"salgados":salgados}) return redirect('/') The default view loads fine. The listar_pizzas in view works fine but when I click submit button it is giving me error like. Page not found (404) Request Method: … -
Django: Check Number of Rows in one model to be less than or equal to value in another model and one field value restricts other field
I have two models (tables) Power_Sources +---------+-------------+--------------------+------------+ | Vehicle | PowerSource | PowerSourceCurrent | NoOfPhases | +---------+-------------+--------------------+------------+ | Lima | Bus | AC | 3 | | Lima | Bus | DC | 1 | +---------+-------------+--------------------+------------+ Power_Sources_Phases +---------+-------------+-------+ | Vehicle | PowerSource | Phase | +---------+-------------+-------+ | Lima | Bus | A | | Lima | Bus | B | | Lima | Bus | C | +---------+-------------+-------+ How do I do the following in the model: Number of rows in Power_Sources_Phases does not exceed Power_Sources.NoOfPhases on (Vehicle and PowerSource) If Power_Sources.PowerSourceCurrent = DC, Power_Sources.NoOfPhases = 1 I'm using Django 3.2 -
Creating Draftail entity with additional data
I've been using Wagtail to create a website with additional text annotations. The user flow is that there is some highlighted text in a paragraph, which when clicked shows an annotation off to one side. The expected HTML result is: A sentence with <span class='link'>A link<span class='hidden-text'>Hidden text</span></span> I would like to achieve this with a single item on the draftail menu, with a UI similar to the URL creator- the user selects the text, and adds the annotation text. I have followed the instructions on https://docs.wagtail.io/en/stable/advanced_topics/customisation/extending_draftail.html to create a new inline style which produces the link, however I can't then add the hidden-text: # 1. Use the register_rich_text_features hook. @hooks.register('register_rich_text_features') def register_mark_feature(features): """ Registering the `mark` feature, which uses the `MARK` Draft.js inline style type, and is stored as HTML with a `<mark>` tag. """ feature_name = 'mark' type_ = 'SAMPLE' tag = 'sample' # 2. Configure how Draftail handles the feature in its toolbar. control = { 'type': type_, 'label': '?', 'description': 'Hint link', } # 3. Call register_editor_plugin to register the configuration for Draftail. features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) # 4.configure the content transform from the DB to the editor and back. db_conversion = { 'from_database_format': {tag: … -
How to make tests for react & django web-application
Is there a specific way to make tests if you are using Django with react? or do I just test them separately? Is there any open source web site on GitHub/gitlab using react and Django as backend that I can use as reference? (I want to look at real code not just example codes)