Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making a table within the Templates folder in Django
I am trying to create a table in Django using a template file I named law.html with data formated in a dataframe from a function I created to scrape information from a public web page. I am trying to use a for loop to iterate through the data but the desired output cannot be achieved for some reason. So far I have a DataFrame called newlaw that is called by the function all_data. The dataframe newlaw is a list of solicitors names and offices. I then imported all_data into my views.py folder and gave it the dictionary 'all_data'. Within my law.html folder I am attempting to create a table using a for loop so that I can have each piece of data in a single cell. The code in my views.py ```def law_view(request, *args, **kwargs): all_data = combine_data() return render(request, "law.html", {'all_data': all_data})``` The code in my law.html ```<table class="table table-striped"> <thead> <tr> <th>Solicitor_Names</th> <th>Offices</th> </tr> </thead> <tbody> {%for solicitor in all_data%} <tr> <td>{{ solicitor }}</td> </tr> {% ednfor %} </tbody> </table>``` This code only prints out the column names. My desired output would look like Solicitor_Name Office John Marston Ernst & Young Amy Smith Kingston Smith .... .... -
Django, Filter a list with AJAX
I am trying to build filter that filters through a list when clicked (option values). Currently the list works using Django's logic, but I need to change it to AJAX (to get more familiar with it). I know that there are other questions similar to this, but I just can't seem to get a hang of it. views.py def gps(request): gps = GoodPractice.objects.all() progr = Programme.objects.all() progr_list = request.GET.getlist("progr") gps = GoodPractice.objects.filter(id__in=ProgrammeList.objects.filter(programme__in=progr_selected).values("goodpractice")).values("name", "country", "programme_type", "what", "id") context = { "active": "gps", "gps": gps, "progr": progr, "progr_list": progr_list, "progr_selected": progr_selected, } return render(request, "gps.html", context=context) This is my script <script> var count = 0; $("#btn-primary").click(function(){ fetchDataAndDisplay(); }); function fetchDataAndDisplay(){ $.ajax({ url:"{% url 'gps/' %}", method:"GET" }).done(function(data){ var start = count > 0 ? 5 * count : count; var end = start + 5; var str = ''; for(var i=start; i<end; i++){ str += '<div class="item-details">' + 'User Id is = ' + data[i].userId + '<br />' + 'Id is= ' + data[i].id + '<br />' + 'Title is = ' + data[i].title + '<br />' + '</div>'; } if(start == data.length){ count = 0; $(".display-data").empty(); $(".display-data").append("List Traversed. Start over!"); return; } count++; $(".display-data").empty(); $(".display-data").append(str); }) } </script> <div class="row"> <div … -
django channels with redis: messages created before websocket connection established are lost
I have managed to get django sending messages to a browser websocket client using channels. But I don't understand it very well. Messages my Celery background task creates before the websocket handshake from the browser do not get shown. messages are sent with async_to_sync(channel_layer.group_send)(str(job.id),..) Django v 2.1.7. The channel layer uses redis so group_send is from channels_redis and the first argument is the group id. I would like a client connecting with the job.id to get all messages ever sent to that group. Does this make sense? -
ManyToManyField in Djnago Rest Framework APIView
I am adding to employee. But it seems ManyToManyField is not working. user_groups Is manytomanyfield. When i am send one group id it is working but when i am trying to send two group id it is not working. It does not give error also userprofile is not created- # Two ids send then response is like this inside "" "user_groups": [ "5,4" ], # One id send then response is like this inside without "" "user_groups": [ 5 ], class EmployeeAddApiV2(APIView): def post(self, request, *args, **kwrgs): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) serializer1 = EmployeeRegisterSerializer(data=request.data) serializer2 = EmployeeProfileSerializer(data=request.data) if serializer1.is_valid(): print(serializer1.validated_data['email']) user = serializer1.save( username = serializer1.validated_data['email'], ) random_password = User.objects.make_random_password() obj = get_object_or_404(User, pk=user.id) obj.set_password(random_password) obj.save() user_role = ACLRoles.objects.get(id=4) if serializer2.is_valid(): serializer2.save( user_id = user.id, user_company_id = accesstoken.application.company.id, user_role_id = user_role.id ) return Response ( { "status" : True, "message":"Employee Added Successfully.", "api_name" : "EmployeeAddApiV2", "result": serializer1.data, "result1": serializer2.data, } ) return Response(status=status.HTTP_404_NOT_FOUND) Serializer.py class EmployeeProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = [ 'user_employee_id', 'user_phone', 'user_payroll_id', 'user_hire_date', 'user_pay_rate', 'user_salaried', 'user_excempt', 'user_groups', 'user_state', 'user_city', 'user_zipcode', 'user_status', … -
I can't get item's to show in my table From database
I was making a Crud in Django but I can't see the items from the database and I can create contracts but can't see them en edit them en delete them. I use this with a javascript code for and ajax that I don't need to reload the page this is my views.py code from django.shortcuts import render # Django # Django from django.contrib.messages.views import SuccessMessageMixin from django.urls import reverse_lazy from django.views import generic # Project from .forms import ContractForm from .models import Contract from bootstrap_modal_forms.mixins import PassRequestMixin, DeleteAjaxMixin class Index(generic.ListView): model = Contract context_object_name = 'contracten' template_name = 'contract/index.html' # Create class ContractCreateView(PassRequestMixin, SuccessMessageMixin, generic.CreateView): template_name = 'contract/create_contract.html' form_class = ContractForm success_message = 'Success: contract aan gemaakt.' success_url = reverse_lazy('index') # Update class ContractUpdateView(PassRequestMixin, SuccessMessageMixin, generic.UpdateView): model = Contract template_name = 'contract/delete_contract.html' form_class = ContractForm success_message = 'Success: contract upgedated.' success_url = reverse_lazy('index') # Read class ContractReadView(generic.DetailView): model = Contract template_name = 'contract/read_contract.html' # Delete class ContractDeleteView(DeleteAjaxMixin, generic.DeleteView): model = Contract template_name = 'contract/delete_contract.html' success_message = 'Success: Book was deleted.' success_url = reverse_lazy('index') def contract(request): return render(request, 'contract/index.html'), my idex.html code {% extends 'base.html' %} {% block content %} {% include "_modal.html" %} <div class="container mt-3"> <div class="row"> <div … -
404 error after changing from aws ec2 to aws s3 the media files url changed
the app was in aws ec2 and all the media file url's are in this format https://example.com/media/k1/literacy/Big_Ben.mp3 and many areusing this url but after changing it into aws s3 the url path has been changed to https://example.s3.amazonaws.com/prod/media/k1/literacy/Big_Ben.mp3 and it shows 404 file not found when accessed by old url. -> How to redirect the old url to new url format when old url has been clicked. -> We cant neglect because many are using the old url. url(r"^media/", '', redirect_to, {'url': 'https://letseduvate.s3.amazonaws.com/prod/media/Grade_1/Maths/BachGavotteShort.mp3'}), import debug_toolbar from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path # For django versions from 2.0 and up from rest_framework_jwt.views import obtain_jwt_token from accounts import views from activity_app.views import authenticate_user from django.views.generic.simple import redirect_to urlpatterns = [ url(r"^admin/doc/", include("django.contrib.admindocs.urls")), url(r"^admin/", admin.site.urls), url(r"^media/", '', redirect_to, {'url': 'https://letseduvate.s3.amazonaws.com/prod/media/Grade_1/Maths/BachGavotteShort.mp3'}), # url(r"^career_app/", include("career_app.urls")), path("__debug__/", include(debug_toolbar.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) when someone uses the old ec2 url it should redirect to new aws s3 urland show the media file. -
Cannot call ModelAdmin.change_view(), ManagementForm data is missing
I am programming a website that displays events. Each occurrence of an event is its own object. Since many of the events are repetitive and it is tedious to re-enter everything and just change the date, I added an occurrence generator, such that the user can set name, location, and time, and then choose a bunch of dates, for which occurrences can be generated with those properties. I have integrated a form for the occurrence generator into the change view of the Event's admin page. I even managed to get it working, even though I encountered a lot of pesty type errors and type-related crashes. (I really wish Django had type hints.) However, in case the submitted occurrence generator form is invalid, Django does not correctly display the change view. It crashes with a validation error, ['ManagementForm data is missing or has been tampered with']. I tried looking through the trace, but I couldn't figure out what is causing it. I am simply passing the invalid form as extra_context, in order for the page to show the errors to the user. admin.py class EventAdmin(admin.ModelAdmin): inlines = [OccurrenceInline] change_form_template = "admin/event_change_form.html" def change_view(self, request, object_id, form_url="", extra_context={}): extra_context["generator_form"] = extra_context.get( "generator_form", … -
Pyinstaller executable giving error on start
I am able to build a exec using pyinstaller but on executing the file using command "q_c runserver localhost:8000" is giving me error "ImportError: No module named 'django.core.management.commands'" My pyinstaller command: pyinstaller --onefile --name=q_c --hidden-import django.contrib.admin.apps -F --hidden-import cymem.cymem --hidden-import thinc.linalg --hidden-import murmurhash.mrmr --hidden-import cytoolz.utils --hidden-import cytoolz._signatures --hidden-import spacy.strings --hidden-import spacy.morphology --hidden-import spacy.lexeme --hidden-import spacy.tokens --hidden-import spacy.gold --hidden-import spacy.tokens.underscore --hidden-import spacy.parts_of_speech --hidden-import dill --hidden-import spacy.tokens.printers --hidden-import spacy.tokens._retokenize --hidden-import spacy.syntax --hidden-import spacy.syntax.stateclass --hidden-import spacy.syntax.transition_system --hidden-import spacy.syntax.nonproj --hidden-import spacy.syntax.nn_parser --hidden-import spacy.syntax.arc_eager --hidden-import thinc.extra.search --hidden-import spacy.syntax._beam_utils --hidden-import spacy.syntax.ner --hidden-import thinc.neural._classes.difference --paths .\env\Lib\site-packages\scipy\extra-dll --hidden-import scipy._lib.messagestream -F --hidden-import sklearn.neighbors.typedefs -F --hidden-import spacy.lang.en -F manage.py My Spec file: # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['.envLibsite-packagesscipyextra-dll', '/tmp/q_c'], binaries=[], datas=[], hiddenimports=['django.contrib.admin.apps', 'cymem.cymem', 'thinc.linalg', 'murmurhash.mrmr', 'cytoolz.utils', 'cytoolz._signatures', 'spacy.strings', 'spacy.morphology', 'spacy.lexeme', 'spacy.tokens', 'spacy.gold', 'spacy.tokens.underscore', 'spacy.parts_of_speech', 'dill', 'spacy.tokens.printers', 'spacy.tokens._retokenize', 'spacy.syntax', 'spacy.syntax.stateclass', 'spacy.syntax.transition_system', 'spacy.syntax.nonproj', 'spacy.syntax.nn_parser', 'spacy.syntax.arc_eager', 'thinc.extra.search', 'spacy.syntax._beam_utils', 'spacy.syntax.ner', 'thinc.neural._classes.difference', 'scipy._lib.messagestream', 'sklearn.neighbors.typedefs', 'spacy.lang.en', 'django.contrib.auth.apps'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='q_c', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) Can someone tell me how to solve this error -
django help loop in formset only returns last index in forms.py
trying to loop over formset forms inside forms.py but it only returns the last index of formset not all of them. forms.py: class MyModelFormSet(BaseModelFormSet): def clean(self): super(MyModelFormSet, self).clean() totalforms = self.total_form_count() #to get number of forms in formset for form in self.forms: for n in range(totalforms): d = self[n].cleaned_data['debit'] # if i use manullay self[0], self[1] it works if d == 100: raise forms.ValidationError('debit is 100!') return d -
how to correctly print json response using python
I have json arrays as follows payload.json {"provision":"provision section 1", "subsets": [{"item":"milk"},{"payments": [{"price": "170 usd"}]}, {"item":"sugar"},{"payments": [{"price": "70 usd"}]}, {"item":"tea"},{"payments": [{"price": "90 usd"}]}]} Here is the code am using to get the json response import json import requests r = requests.get('http://localhost/payload.json') stat=r.status_code head=r.headers['content-type'] encode=r.encoding texting=r.text result=r.json() print(stat) print(head) print(texting) print(result) I can successfully get the results in json My requirements: How do I successfully loops to print out values for Provisions, item and price. If i try something like print(result.provision), it will display error dict object has no attribute provision -
Django- render to pdf with button
I have def that render to pdf with action on django-admin. def Print(self, request, obj): data = { 'obj':obj } pdf = render_to_pdf('daa/imprimir/pdf.html', data) if pdf : response = HttpResponse(pdf, content_type='application/pdf') filename ="Avaria_%s.pdf" %("123451231") content = "inline; filename='%s'" %(filename) response['Content-Disposition'] = content download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and on my actions I have: class ModelAdmin(admin.ModelAdmin): actions = [Print] and it is working all good, I select what objects I want to render and in my html I have cicles that make a list of all fields I want of those obj's. But right now I don't want to render to pdf a list. I want to render only 1 obj. So I create a custom button to do that. http://prntscr.com/muijhl So when I click on button I want to render to pdf the obj which is open. I don't know what I need to do to take my def and but inside of button -
How to add local client file browsing in Django?
All topics I find related to my question focus on implementing a user file storage on server side with Django. This is just partlywise what i need. I want to be able that a user can browse (like in a file explorer) it's own network drives - at least some added directory paths on client side. I guess that i can't make it work without any Javascript. Do you know any examples on how to implement a local file browsing with django? Can you provide me with some good code examples? Thank you for any suggestions -
Function in django views run 2 times without reason
I have problem because I can not find the reason why my function in django views sometimes runs two times. When I go to url, which call function create_db in djnago view, function read json files from directory, parse it and write the data in the database. Most of the time it works perfectly, but sometimes for no reason it runs two times and write the same data in the data base. Does anyone know what can be the reason why code is sometimes done twice? Here is my create_db function: def create_db(request): response_data = {} try: start = time.time() files = os.listdir() print(files) for filename in files: if filename.endswith('.json'): print(filename) with open(f'{filename.strip()}', encoding='utf-8') as f: data = json.load(f) for item in data["CVE_Items"]: import_item(item) response_data['result'] = 'Success' response_data['message'] = 'Baza podatkov je ustvarjena.' except KeyError: response_data['result'] = 'Error' response_data['message'] = 'Prislo je do napake! Podatki niso bili uvozeno!' -
Setting up django crowd authentification proxy issues
I am trying to authentificate user to crowd service using this packages : https://pypi.org/project/django-crowd-auth/ django-rest-jwt I work behind a proxy using CNTLM : i configured os environnement variables to point out to CNTLM pip install works fine I used for my app the settings provided by the example of the crowd-django packages When i try to auth with creditentials in /auth i've got the follwing error: Error: HTTPSConnectionPool(host='xxxx',port=xxx):Max retries exceed with url : /mycrowdEndpoint/cookie.json (Caused by ProxyError('cannot connect to proxy'),timeout('timed out') I expect to auth in django app users using CROWD service -
I am not getting distinct result with related field
models.py class PlayLists(models.Model): name = models.CharField(max_length=256, null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) class PlayListVideos(models.Model): coach = models.ForeignKey(coachRegister, on_delete=models.CASCADE, related_name='playlist_videos',null=True,blank=True) video = models.ForeignKey(VideosModel, on_delete=models.CASCADE, related_name='playlists_videos',null=True,blank=True) playlist = models.ForeignKey(PlayLists, on_delete=models.CASCADE, related_name='playlists_videos',null=True,blank=True) views.py from .models import PlayListVideos from django.http import JsonResponse from django.db.models import count def playlists(request): res = list(PlayListVideos.objects.values('playlist__name','video__url','video__title').annotate(videos=Count('playlist__name'))) return JsonResponse(res, safe=False) getting result: [ { "video__url": "DX-FIfLb19A", "videos": 1, "playlist__name": "game of thrones", "video__title": "70th Emmy Awards: Peter Dinklage Wins For Outstanding Supporting Actor In A Drama Series" }, { "video__url": "rlesc2MYVoA", "videos": 1, "playlist__name": "game of thrones", "video__title": "Game of Thrones 7x05 - Jon Snow meets Drogon - Daenerys reunites with Jorah" }, { "video__url": "mk1DXwb-XbM", "videos": 1, "playlist__name": "mylist", "video__title": "Game of Thrones 7x03 - Jon Snow meets Daenerys Targaryen" } ] expecting result: [ { "video__url":[ "rlesc2MYVoA", "DX-FIfLb19A" ], "videos": 2, "playlist__name": "game of thrones", "video__title":[ "70th Emmy Awards: Peter Dinklage Wins For Outstanding Supporting Actor In A Drama Series", "Game of Thrones 7x05 - Jon Snow meets Drogon - Daenerys reunites with Jorah" ] }, { "video__url":[ "mk1DXwb-XbM" ], "videos": 1, "playlist__name": "mylist", "video__title":[ "Game of Thrones 7x03 - Jon Snow meets Daenerys Targaryen" ] } ] Here i am expecting distinct result as per playlist__name and i … -
Editing other user's profile like we do in admin page
I am relatively new to django and I want to implement this functionality So basically I want to create a listview of all Users from where I want to select any particular User which will take me to that User's Updateview and I want to give that right to only superuser. Note:I have an AbstractUser the code I have tried is below: view.py class editinfo(UpdateView,LoginRequiredMixin): model=User form_class=forms.UserProfileForm success_url=reverse_lazy('home') template_name='accounts/edit.html' def get_queryset(self): queryset=super().get_queryset() return queryset.filter(username__iexact=self.kwargs.get('username')) class userlist(ListView): model=User template_name='accounts/user_list.html' def get_queryset(self): try: self.user_all = User.objects.all() except User.DoesNotExist: raise Http404 else: return self.user_all def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) context['user_all']=self.user_all return context urls.py path('edit/<int:pk>/',views.editinfo.as_view(),name='edituser'), path('user/all/',views.userlist.as_view(),name='userlist'), forms.py class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('username','email','first_name','last_name','mobilenumber','address','designation', 'password', 'is_active','is_staff') def save(self, user=None): user_profile = super(UserProfileForm, self).save(commit=False) user_profile.save() return user_profile edit.html {% extends "base.html" %} {% load crispy_forms_tags %} {% load staticfiles %} {% block content %} <div class="container"> <h1>Update Info</h1> <form method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class='btn btn-default' value="Update"> </form> </div> {% endblock %} user_list.html {% extends "base.html" %} {% block content %} <div class=" container"> <h3>User List</h3> {% if user.is_authenticated and user.is_superuser %} <ul> {% for user in user_all %} <li><a href="{% url 'accounts:edituser' pk=user.pk %}">@{{ user.username }}</a> </li> {% endfor … -
Update Using APIView
I am trying to update Employee. For that i am using two serializers where UserProfile model is related with OneToOneField with User model. But the problem is coming while updating. When i am updating the Employee Serializer1 is working but serializer2 is not working. I don't know what is the problem. user_id = request.data['user_id'] user = get_object_or_404(User, id=user_id) print(user) userprofile = get_object_or_404(UserProfile, user=user_id) print(request.data) serializer1 = EmployeeRegisterSerializer(user, data=request.data) serializer2 = EmployeeProfileSerializer(userprofile, data=request.data) EmployeeProfileSerializer this not working while updating. It is working while adding employee class EmployeeUpdateApiV2(APIView): def post(self, request, *args, **kwrgs): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) user_id = request.data['user_id'] user = get_object_or_404(User, id=user_id) print(user) userprofile = get_object_or_404(UserProfile, user=user_id) print(request.data) serializer1 = EmployeeRegisterSerializer(user, data=request.data) serializer2 = EmployeeProfileSerializer(userprofile, data=request.data) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() serializer2.save() print('Inside Valid') return Response ( { "status" : True, "message":"Employee Updated Successfully.", "api_name" : "EmployeeUpdateApiV2", "result": serializer1.data, "result1": serializer2.data, } ) print('Out Valid') print('serializer1 ', serializer1.errors) print('serializer2', serializer2.errors) return Response(status=status.HTTP_404_NOT_FOUND) These are my Serilizers class EmployeeProfileSerializer(serializers.ModelSerializer): employee_id = serializers.CharField(source='user_employee_id', required=False) payroll_id = serializers.CharField(source='user_payroll_id', required=False) hire_date = serializers.CharField(source='user_hire_date', required=False) pay_rate = serializers.CharField(source='user_pay_rate', required=False) salaried = … -
Digital Freight Marketplace
I am trying to create a model in which manufacturers can post a shipment which needs to be transported and transporter can post that his truck is going from point A to point B. If the Origin, Destination, and load(to be transported and truck capacity) matches then both of them are notified a match. I have tried researching on automatic matching but the closest I come to is the Hungarian Algorithm that solves the assignment problem, but I am not so sure if it's the right direction or not. In the model, I have already created input forms for both sections i.e. manufacturers and transporters and the data is saved in a Database. I am thinking of applying a trigger function which rechecks for the best match every time when a new entry comes in Database Here is the Data from both input forms: Manufacturer M_ID From To M_Type T_Type T_Length T_Weight #Trucks Loading_Time 1025 A B Boxes Open 12-Tyre 22 3 27-March-2019 6:00PM 1029 C D Cylinders Trailer HIGH 23 2 28-March-2019 6:00PM 1989 G H Scrap Open 14-Tyre 25 5 26-March-2019 9:00PM Transporter T_ID From To T_Type T_Length T_Weight #Trucks Price 6569 A B Open 12-Tyre 22 5 … -
Django - How can users view books under his membership type?
I set up memberships for users so that they can have an option to view selected books under a certain membership type. In this case how can a user view the list of books under his membership type within his profile page? Here are my codes for books: class Book(models.Model): ``` some book fields``` activeReference = models.ManyToManyField(Membership) #here's where membership connects```` def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) Here are for the models for membership: class Membership(models.Model): membership_type = models.CharField(max_length=50) price = models.IntegerField(default=100) description = models.CharField(max_length=200) def __str__(self): return self.membership_type class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.CASCADE, null=True) reference = models.CharField(max_length=50, null=True) def __str__(self): return self.user.email And here's the view for profile: def profile(request): ```some update profile post code here``` context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) I expect for the user to view all his books under his membership type. -
Django. How to display fields of the current category in the template?
I need to make sure that the template displays only the data that relates to the current category of real estate. This is views.py: def category_view(request, category_slug): feedbacks = Feedback.objects.all() categories = Category.objects.all() category = Category.objects.get(slug=category_slug) listings_of_category = category.listing_set.all().filter(name=category.name) context = { 'feedbacks': feedbacks, 'categories': categories, 'category': category, 'listings_of_category': listings_of_category } return render(request, 'pages/category.html', context) Maby it should be conditious in template... Template of lising: <div class="col-md-6"> <ul class="list-group list-group-flush"> <li class="list-group-item text-secondary"> <i class="fas fa-money-bill-alt"></i> Запрашиваемая цена: <span class="float-right">${{ listing.price | intcomma }} </span> </li> {% if listings_of_category %} <li class="list-group-item text-secondary"> <i class="fas fa-house"></i> Серия: <span class="float-right">{{ listing.flat_type }}</span> </li> {% endif %} <li class="list-group-item text-secondary"> <i class="fas fa-bed"></i> Комнаты: <span class="float-right">{{ listing.rooms }}</span> </li> <li class="list-group-item text-secondary"> <i class="fas fa-step-forward"></i> Количество этажей: <span class="float-right">{{ listing.stage_quantity }} </span> </li> <li class="list-group-item text-secondary"> <i class="fas fa-step-forward"></i> Этаж: <span class="float-right">{{ listing.stage }}</span> </li> <li class="list-group-item text-secondary"> <i class="fas fa-car"></i> Гараж: <span class="float-right">{{ listing.garage }} </span> </li> </ul> </div> Main model: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район') title = models.CharField(max_length=200, verbose_name='Заголовок') address = models.CharField(blank=True, max_length=200, verbose_name='Адрес') description = models.TextField(blank=True, verbose_name='Описание') … -
php session_name alternative for django
In php you can set a session name using session_name, do we've anything similar in Django (python) application? I don't want to set anything at the global level for whole application level, for only some pages just like session_name does in php. Regards -
How to create a table with multiple columns with data from the same list?
I am trying to create a table with HTML tags but I am stuck with it. I tried to play with {% for i in list %}, but I couldn't find a solution. list = {'ticker': tickers, 'price': prices} <tbody> <tr> {% for i in price %} <td>{{ i }}</td> {% endfor %} {% for i in ticker %} <td>{{ i }}</td> {% endfor %} </tr> <tr> </tr> </tbody> I would see 2 columns one close to another, but I don't see any columns now. -
How to upload a custom excel file via django?
Currently I am starting to develop a django project which need to provide a HTML page for other students to upload their experiment results which are excel files (maybe CSV), and save them to databases. But I don't know what should I do with the model.py file for each student have diffenent assignments which means the first row of different experiments are not the same. Can anyone help me? Django 2.1.7 -
Does update method acquire lock on the matched row when called from transaction.atomic() block - Django
Does calling update method from inside transaction.atomic() acquire lock on the row that matches the filter condition? I understand that select_for_update acquires lock on all the rows that match the criteria until exiting from atomic block. -
Django refuse to connect HTML that without have HTTP protocol
Hi I wish to IFRAME HTML code in my django, but unfortunately it fail to show out contain. template.html <iframe id="inlineFrameExample" title="Inline Frame Example" width="300" height="200" src="https://www.openstreetmap.org/export/embed.html?bbox=-0.004017949104309083%2C51.47612752641776%2C0.00030577182769775396%2C51.478569861898606&layer=mapnik"> </iframe> <iframe id="inlineFrameExample" title="Inline Frame Example" width="300" height="200" src="C:/Graph/GraphCombine/templates/T.html"> </iframe> For the first IFRAME it work, but for the second iframe, the content are not showing up,anyone can share me ideas?