Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React JS - Capturing selected items from SELECT Multiple field
I'm using a form where an admin can create a class and add students to the class. I'm using SELECT multiple to allow the admin to select multiple students. My question is how do I capture the selected range and export that to a list. I have tried to use dataset but no luck. function ClassesCreate(props) { const [token, setToken] = useState(""); const [hasToken, setHasToken] = useState(""); useEffect(() => { if(localStorage.getItem("token")){ setToken(localStorage.getItem("token")); setHasToken(true); } }, []); function createClasses(){ let login_token = localStorage.getItem("token") let data={ class_number:document.getElementById("ClassNumber").value, course:document.getElementById("Course").value, semester:document.getElementById("Semester").value, lecturer:document.getElementById("Lecturer").value, student:document.getElementById("Student").dataset } axios.post(BaseUrl+"attendance/classes_viewset/", data, {headers:{ "Authorization": "Token "+login_token }}).then(response=>{ alert("Create successful") }).catch(error=>{ console.log(error) }) } return ( <div> <p>Class Number: <input type={"text"} id={"ClassNumber"}/> </p> <p> Course: <select id={"Course"}> <Course/> </select> </p> <p> Semester: <select id={"Semester"}> <Semester/> </select> </p> <p> Lecturer: <select id={"Lecturer"}> <Lecturer/> </select> </p> <p> Students: <select id={"Student"} multiple > <Student/> </select> </p> <p> <button className={"btn btn-danger"} onClick={createClasses}>Create</button> </p> </div> ); } export default ClassesCreate; INSPECT/CONSOLE from browser AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 400" name : … -
Django Redis problem with Docker: InvalidCacheBackendError: No module named 'django.core.cache.backends.redis'
StackOverflow! This is the first question I am asking but I have received many other answers from here thanks a lot. So my problem is that I want to use Redis through docker for the cache but got this error. django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django.core.cache.backends.redis.RedisCache': No module named 'django.core.cache.backends.redis' My cache settings are this. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', } } I took them from Django documentation. I used this command to start a Redis instance in docker. docker run --name some-redis -d redis I saw a few older posts that didn't help me with the problem. -
How to escape double quotation symbol during lambda apply operation on dataframe column?
I have a pandas column, in which I want to replace the strings with a href hyperlinks that link to a certain url in urls.py when using Django. I managed to get the following: import pandas as pd df = pd.DataFrame(["2022-007", "2022-008", "2022-111", "2022-222", "2022-555", "2022-151"], columns=["column_of_interest"]) df["column_of_interest"] = df['column_of_interest'].apply(lambda x: '<a href=' "{{% url 'columndetails' {0}%}}" '>{0}</a>'.format(x)) This results for example in the following: df["column_of_interest"][0] "<a href={% url 'columndetails' 2022-007%}>2022-007</a>" However, when I run this in Django, and try to get the redirect the following error occurs: Request URL: http://127.0.0.1:8000/%7B%25 The current path, {%, didn’t match any of these. I think this problem would be resolved if I can manage to get this output as per the Django docs: df["column_of_interest"][0] "<a href="{% url 'columndetails' 2022-007%}">2022-007</a>" ↑ ↑ How can I change my .apply(lambda x) to include double quotation marks before and after the {}? I tried escaping with \\ and throwing round the single and double quotation marks, but can't seem to solve this problem easily. -
How to run javascript through the for loop?
I created a search and highlight field for my model objects. The page takes a text input and filters the objects like Documents.objects.filter(content) I'm using read more and highlight functions to highlight the input word and show the part of the long content. But I can't click some read-mores on the row. For example, I can't click the 1st and 3rd row (it returns javascript:void(0) but there is no action) but I can click the other rows. How can I fix that? <div id="highlights" > <div class="row"> <div class="col-md-12" > <div class="box"> <p class="countParawords-{{ forloop.counter0 }}" id="paragraph-{{ forloop.counter0 }}"> {{ document.content }} </p> </div> </div> <input id="typed-text-{{ forloop.counter0 }}" type="text" class="hidden_input" placeholder="Type text" value="{{ key_word }}"> </div> </div> <script> {% for doc in documents %} var opar = document.getElementById('paragraph-{{ forloop.counter0 }}').innerHTML; $(document).ready(function() { var maxLength = 300; var moretxt = "...Read More"; var lesstxt = "...Read Less"; $(".countParawords-{{ forloop.counter0 }}").each(function() { if(opar) { var paragraph = (document.getElementById('paragraph-{{ forloop.counter0 }}')); var search = document.getElementById('typed-text-{{ forloop.counter0 }}').value; search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); var re = new RegExp(search, 'g'); if (search.length > 0) paragraph.innerHTML = opar.replace(re, `<span style="background: #cead00">$&</span>`); } else{ console.log("No data") } var myStr = paragraph.innerHTML if ($.trim(myStr).length > maxLength) { var … -
With drf-yasg, how can i show multiple openapi schemes?
Used: Django 2.2, drf-yasg 1.17.1, python 3.9 How can I show with drf-yasg multiple openapi schemes? API returning different responses, depending on the request. Example: Basic response Is it possible in drf-yasg to show responses like this? Expected Result In the yaml file, this is implemented using oneOf. Code example: responses: '200': content: application/json: schema: properties: count: type: integer next: type: string previous: type: string results: oneOf: - $ref: '#/components/schemas/BaseStocks' - $ref: '#/components/schemas/Apteka36.6Stocks' - $ref: '#/components/schemas/FarmiyaStocks' - $ref: '#/components/schemas/MailruStocks' - $ref: '#/components/schemas/NeofarmStocks' - $ref: '#/components/schemas/YandexStock' - $ref: '#/components/schemas/UtekaStocks' Is it possible to repeat such a construction with drf-yasg? -
Django Rest Framework Post API Method Not Working
I am new to DRF and am trying to create four basic API methods for my Company model. GET, PUT, and DELETE are working fine. However, I am having issue with POST. When I test it with Postman it "kinda" saves the object in the Database, but with null values and not with ones that I entered. Only values that it saves that are not null are ID (which is saved automatically by default) and image field because I set the default image. I am using PostgreSQL DB, and below are my models.py, serializers.py, views.py, and urls.py. models.py `#Companies #File Location Function def upload_location(instance, filename, **kwargs): file_path = 'company/{company_name}-{filename}'.format( company_name = str(instance.name), filename = filename ) return file_path class Companies(models.Model): STATUS = ( ("Active", "Active"), ("Inactive", "Inactive") ) #Basic fields code = models.CharField(max_length=30, unique=True, null=True, verbose_name="Company Code ") name = models.CharField(max_length=100, unique=True, verbose_name='Company Name ', null=True) address = models.CharField(max_length=100, unique=True, verbose_name='Address ', blank=True, null=True) city = models.CharField(max_length=100, verbose_name='City ', blank=True, null=True) zip_code = models.CharField(max_length=10, verbose_name='Zip Code ', blank=True, null=True) country = models.CharField(max_length=100, verbose_name='Country ', blank=True, null=True) default_email = models.CharField(max_length=100, unique=True, verbose_name='Default E-mail ', blank=True, null=True) default_phone = models.CharField(max_length=100, unique=True, verbose_name='Default Phone Number ', blank=True, null=True) id_number = models.IntegerField(unique=True, verbose_name='ID Number … -
TemplateDoesNotExist at / customer/index.html Request Method
i get the error of Template does not exist # [[e](https://i.stack.imgur.com/gSKFa.png)](https://i.stack.imgur.com/795HN.png) this is my urls when i run i get the error emplateDoesNotExist at / customer/index.html Request Method from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from customer.views import Index, About urlpatterns = [ path('admin/', admin.site.urls), path('', Index.as_view(), name='index'), path('about/', About.as_view(), name='about'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
I am deleting the object from my database using delete button made in angular 13, but this does not delete it instantly from frontend
i need to delete the object real-time from frontend as well as backend my, The object gets deleted from the backend instantly but it do not reflects in the frontend till the page is refreshed //delete component deleteStory(id : string){ console.log(id) this.storyapiService.deleteStory(id).subscribe(); } service.ts deleteStory(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id); } //html <button class="btn btn-primary" (click)="deleteStory(story.id)" style="margin-left:5px">Delete </button> -
How can get selected item from auto fields on many to many relationship (django Admin Model)
I'm new in django. I want to create several sub-categories with django-mptt, and on the Django management page, when creating a product, the main categories will be searched first, then searched subcategories under selected main category, and so on. Like a tree, at each step, according to the selected node, the child nodes are searched. Photo description My problem is I don't know how to get selected item then filter search fields from category model. in models.py my app from mptt.models import MPTTModel, TreeForeignKey class Movie(models.Model): title = models.CharField(max_length=255) genre = models.ManyToManyField("Genre") def __str__(self): return self.title class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") class MPTTMeta: order_insertion_by = ["name"] def __str__(self): return self.name and in admin.py my app from mptt.admin import DraggableMPTTAdmin @admin.register(Genre) class AdminGenre(DraggableMPTTAdmin): list_display = ["tree_actions", "indented_title"] list_display_links = ["indented_title"] search_fields = ["name__istartswith"] def get_search_results(self, request, queryset, search_term): # return super().get_search_results(request, queryset.get_descendants(), search_term) return super().get_search_results(request, queryset, search_term) @admin.register(Movie) class AdminMovie(admin.ModelAdmin): autocomplete_fields = ["genre"] How can get selected item from django admin in create page. Just search on rock's children -
Create multiple objects in one form Django
I am trying to create a form in Django that can create one Student object with two Contact objects in the same form. The second Contact object must be optional to fill in (not required). Schematic view of the objects created in the single form: Contact 1 Student < Contact 2 (not required) I have the following models in models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): ACCOUNT_STATUS_CHOICES = ( ('A', 'Active'), ('S', 'Suspended'), ('D', 'Deactivated'), ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) year = models.ForeignKey(Year, on_delete=models.SET_NULL, null=True) school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) student_email = models.EmailField() # named student_email because email conflicts with user email account_status = models.CharField(max_length=1, choices=ACCOUNT_STATUS_CHOICES) phone_number = models.CharField(max_length=50) homework_coach = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, blank=True, default='') user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) plannings = models.ForeignKey(Planning, on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Contact(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) contact_first_name = models.CharField(max_length=50) contact_last_name = models.CharField(max_length=50) contact_phone_number = models.CharField(max_length=50) contact_email = models.EmailField() contact_street = models.CharField(max_length=100) contact_street_number = models.CharField(max_length=10) contact_zipcode = models.CharField(max_length=30) contact_city = models.CharField(max_length=100) def __str__(self): return f"{self.contact_first_name} {self.contact_last_name}" In forms.py, I have created two forms to register students and contacts. A student is also connected to a User object for login and authentication, but this is … -
AssertionError when reloading page
I am writing a human detection live streaming with Django + YOLOv5, firstly i import the video source form rtsp, then detect with run() function, then yield frame by frame. To stream, i use StreamingHttpResponse with streaming_content=run(). It seems to work fine, but when i reload the streaming page, maybe the run() is called again, if i reload too much, the fps decreases then the stream stops, with an AssertionError: cannot open rtsp... I have try some solution, use iframe on front-end,... but every time front-end show the stream, it calls StreamingHttpRespone and run() again, do you have any solution for it? def video_feed(request): return StreamingHttpResponse(streaming_content=run(), content_type='multipart/x-mixed-replace; boundary=frame') -
Encapsulating the pythonping function in DJango framework
I have been building a web app using the Django framework to allow me to ping certain IPs periodically to see if they are online. The setup of the app requires different IPs in different groups. When I have added the python ping function into my model it says that the IPs are not reachable. Below is my models.py for the project. As you can see I have included the pythonping ping function to try and ping the IPs in question, but it does not seem to work. from cgitb import text from ipaddress import ip_address from django.db import models from pythonping import ping #import macaddress # Create your models here. class WS_Building_location(models.Model): Building = models.CharField(max_length=200) #date_added = models.DateTimeField(auto_now_add =True) class Meta: verbose_name_plural = 'Buildings' def __str__(self): return self.Building class WS_address(models.Model): """Wyrestorm address""" building = models.ForeignKey(WS_Building_location, on_delete=models.CASCADE) ws_ip = models.GenericIPAddressField() #mac_address = models.macaddress() date_added = models.DateTimeField(auto_now_add=True) ipstr = str(ws_ip) ip_ping = models.TextField(ping('ipstr', verbose = False)) class Meta: verbose_name_plural = 'addresses' def __str__(self): return self.ws_ip I have read that the pythonping module needs to have root access in order to create the raw packets it uses as a ping and it is not recommended that django be root for security concerns. … -
django.template.exceptions.TemplateSyntaxError: Invalid block tag. Did you forget to register or load this tag?
I have a view that has context data and it extends base.html but as I want the context data to be displayed in all templates that extend from base.html and not only the view with the context data I am doing custom template tags with the context inside but I get an error. view with and without context data: class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' paginate_by = 25 class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' paginate_by = 25 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() news = News.objects.all() context.update({ 'categories' : categories, 'news' : news, }) return context base.html with and without the custom tag {% news %} {% for new in news %} <p>{{ new.title }}</p> {% endfor %} The custom tag file templatetags/news.py from django import template from support.models import News register = template.Library() @register.inclusion_tag('news.html', takes_context=True) def news(context): return { 'news': News.objects.order_by("-date_posted")[0:25], } The custom tag file templatetags/news.html {% for new in news %} <p>{{ new.title }}</p> {% endfor %} -
Django class based signup view form not show up in bootstrap modal
I try to look up my signup view as a bootstrap modal but when click form doesn't show [my views.py[modal form look[index.htmlmy signup.html](https://i.stack.imgur.com/qv1BD.png)](https://i.stack.imgur.com/b7ChP.png)](https://i.stack.imgur.com/BMlaq.png) Can I figure it out without using Ajax or something else or do I have to change my signup view from class based views to something else -
Is Django serializer escaping characters to protect from xss attack?
I use a serializer to process the data comming from the frontend. The data is basically a username, email and password. The data will be saved in a database and the username will be displayed in the frontend later on. I am wondering if the serializer is already escaping " and < characters to protect from xss-attacks. If it isn't, is there a simple way to configure the serializer to do so? My serializer looks like that: # Register Serializer class RegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) profile_data = validated_data.pop('profile') user.profile.company_name = profile_data['company_name'] user.is_active = False user.save() return user -
django-filebrowser-no-grappelli - problem with AzureStorage
I installed django-filebrowser-no-grappelli and added AzureBlobStorageMixin from django-filebrowser-no-grappelli2, link here. The problem is that I cannot create any folder and upload any image through admin panel. I get this error: This backend doesn't support absolute paths. When I try to create new folder I get: 'AzureMediaStorage' object has no attribute 'service' Below is the code with class AzureBlobStorageMixin(StorageMixin): storage_type = 'azure' def sys_file(self): return 'dir.azr' def isdir(self, name): """ Returns true if name exists and is a directory. """ if name.endswith('/'): return True result = self.listdir(name) # if name contains dirs (result[0]) or files (result[1]) its a directory return len(result[0]) > 0 or len(result[1]) > 0 def isfile(self, name): """ Returns true if name exists and is a regular file. """ return self.exists(name) def listdir(self, path=''): files = [] dirs = [] path_parts = path.split('/') # remove blank parts of path if path_parts[-1] == '': path_parts = path_parts[:-1] for name in self.list_all(path): name_parts = name.split('/') # check dir level of files if len(name_parts) == len(path_parts) + 1: files.append(name_parts[-1]) # check dir level of dirs elif len(name_parts) == len(path_parts) + 2: if name_parts[-2] not in dirs: dirs.append(name_parts[-2]) else: pass return dirs, files def path(self, name): """ Azure storage doesn't support Python's … -
How to NOT "double-encode" UTF-8 strings in a custom Django lookup (rhs)
Suppose the following custom Django lookup: from django.db import models class WebSearch(models.Lookup): lookup_name = 'websearch' def as_postgresql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return """to_tsvector('french', (%s)) @@ websearch_to_tsquery('french', (%s))""" % (lhs, rhs), params Now, querying a model TextField like so: MyModel.objects.filter(sometextfield__websearch='sautée') results in the following SQL: SELECT * FROM mymodel WHERE to_tsvector('french', ("sometextfield")) @@ websearch_to_tsquery('french', ('"saut\\u00e9e"')) which added double quotes around rhs, changing the semantics of websearch_to_tsquery encoded the UTF-8 character in a weird way while Postgres CLI (psql) seems to support just straight up querying like so: SELECT * FROM mymodel WHERE to_tsvector('french', "sometextfield") @@ websearch_to_tsquery('french', 'sautée'); How would one disable all that string encoding business, so that "sautée" would just come out as "sautée"? -
How to display property method as a message in class based view?
I have a property method defined inside my django model which represents an id. status_choice = [("Pending","Pending"), ("In progress", "In progress") ,("Fixed","Fixed"),("Not Fixed","Not Fixed")] class Bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='assigned', null = True, blank=True) phn_number = PhoneNumberField() uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='user_name') created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(blank= True, null = True) updated_by = models.CharField(max_length=20, blank= True) screeenshot = models.ImageField(upload_to='pics') @property def bug_id(self): bugid = "BUG{:03d}".format(self.id) return bugid What I wanted is I need to show this id as a message after an object is created. corresponding views.py file. class BugUpload(LoginRequiredMixin, generic.CreateView): login_url = 'Login' model = Bug form_class = UploadForm template_name = 'upload.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.uploaded_by = self.request.user return super().form_valid(form) -
How to get list of users by passing permissions and roles string in Django
I searched many links over here. I don't know how to write the above functionality using Django. I wanted to list all the user by permissions or roles in Django. Read many blogs and we have option to get the list of permission or roles assigned to the user and not vice versa. Let me know the other options to get the same. -
drf_yasg: How to add square backets in TYPE_ARRAY parameters when request from swagger ui
I have custom field in request body: receipt_details_schema = openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'bonus_restrict': openapi.Schema( title='bonus_restrict', type=openapi.TYPE_INTEGER ), 'prod_cat': openapi.Schema( title='prod_cat', type=openapi.TYPE_INTEGER ), 'prod_code': openapi.Schema( title='prod_code', type=openapi.TYPE_INTEGER ), 'prod_name': openapi.Schema( title='prod_name', type=openapi.TYPE_STRING ), 'prod_price': openapi.Schema( title='prod_price', type=openapi.TYPE_INTEGER ), 'prod_amount': openapi.Schema( title='prod_amount', type=openapi.TYPE_INTEGER ), 'prod_sum': openapi.Schema( title='prod_sum', type=openapi.TYPE_INTEGER ), 'position': openapi.Schema( title='position', type=openapi.TYPE_INTEGER ), }, required=['prod_code', 'prod_price', 'prod_amount', 'prod_sum', 'position'], ) receipt_details_field = openapi.Parameter( name='receipt_details', in_=openapi.IN_FORM, description="receipt_details field", type=openapi.TYPE_ARRAY, items=receipt_details_schema # schema=receipt_details_schema, ) @swagger_auto_schema(manual_parameters=[receipt_details_field]) def post(self, request, **kwargs): and when trying request from swagger ui with header(x-www-urlencoded), i get data field whithout square backet. How i can add it with objects when requesting? enter image description here enter image description here I check drf_yasg documentation and not find answer for my quetion. I'm beginner in drf, dont scold me. -
Why is it not redirected when the payment is successful? using django and braintree dropin-ui
I use this sandbox for the payment section of the store site. I want to redirect the user to page Done after successful payment, but the current page is loaded again! pealse help view of payment_process: def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': nonce = request.POST.get('paymentMethodNonce', None) result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: order.paid = True order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token}) page of Done.html: {% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %} <h1>Pay by credit card</h1> <!-- includes the Braintree JS client SDK --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://js.braintreegateway.com/web/dropin/1.14.1/js/dropin.min.js"></script> <form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">&times;</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } … -
django project : An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
Slut everyone, in this django project I'm trying to save or update my database with data from an API.Here is the structure of my models models.py def A(models.Model): number=models.CharField(max_length=50,blank=True,null=True,unique=True) sayfa=CharField(max_length=100,blank=True,null=True) def B(models.Model): link=models.ForeignKey(A, on_delete=models.CASCADE) adress=models.CharField(max_length=255,blank=True,null=True) in this specific case, each element of A can contain several rows of B. And as the data comes from an API, I would like to save it at my database level and if the element exists it updates it views.py def test(request): url='http://myapi/data' x=requests.get(url) contenu=x.json() all_data=content['data'] for my_data in all_data: bv, _ = B.objects.update_or_create(adress=my_data['adress']) bv.save() mala=B.objects.all() context={'data':mala} return render(request,'account/list.html',context) when executing i get the error (An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.) Here each row of A can have several rows at table B. -
Accessing Mailman 3 list members via Python/Django management console
I am trying to access members of an existing Mailman 3 mailing list directly from Django Management console on a Debian Bullseye where Mailman is installed from deb packages (mailman3-full). I can connect to the Django admin console like this (all 3 variants seem to work fine): $ /usr/share/mailman3-web/manage.py shell $ mailman-web shell $ mailman-web shell --settings /etc/mailman3/mailman-web.py Python 3.9.2 (default, Feb 28 2021, 17:03:44) >>> But inside the Django admin console, some mailman components seem to be missing. I try to access the list manager as described here: Docs > Models > The mailing list manager: >>> from mailman.interfaces.listmanager import IListManager >>> from zope.component import getUtility >>> list_manager = getUtility(IListManager) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python3/dist-packages/zope/component/_api.py", line 169, in getUtility raise ComponentLookupError(interface, name) zope.interface.interfaces.ComponentLookupError: (<InterfaceClass mailman.interfaces.listmanager.IListManager>, '') Can't figure out why this ComponentLookupError happens. Also tried to acccess a list with the ListManager implementation: >>> from mailman.config import config >>> from mailman.model.listmanager import ListManager >>> list_manager = ListManager() >>> list_manager.get('mynews@example.com') Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python3/dist-packages/mailman/database/transaction.py", line 85, in wrapper return function(args[0], config.db.store, *args[1:], **kws) AttributeError: 'NoneType' object has no attribute 'store' >>> list_manager.get_by_list_id('mynews.example.com') Traceback … -
How i can fix Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text
Python django when I starting local sever, I met only Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text how can i fix? window error at first the problem was about direcotry, so read and search about django slash document. and then i ment a new problem rn.. -
Django orm "annotate" not working with "only"
I want to select only one column with "only" and rename it. The code I want in SQLServer is as follows: SELECT [table].[col1] AS [new_col1] FROM [table] in django orm: model.objects.annotate(new_col1=F('col1').only('col1')).all() When i change it to sql query it is like this: SELECT [table].[col1], [table].[col1] AS [new_col1] FROM [table] and below orm code not working: model.objects.annotate(new_col1=F('col1').only('new_col1')).all() I don't want to use "vales" or "values_list". Please help me how I can do it.