Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
increment 30 minutes in time in loop append in list in django
Need to add the time in list from starting time and ending time given timing = timings.objects.all() monday_time = timing.monday_time teusday_time = timing.teuday_time ... x = monday_time + datetime.time('00:30') This is not working , this give the error of typeError, How to increment time and add on list. -
Obtain the last value from every sensor on my django model
I am working with Django and I am a bit lost on how to extract information from models (tables). I have a table containing different information from various sensors. What I would like to know is if it is possible from the Django models to obtain for each sensor (each sensor has an identifier) the last row of data (using the timestamp column). In sql it would be something like this, (probably the query is not correct but I think you can understand what I'm trying) SELECT sensorID,timestamp,sensorField1,sensorField2 FROM sensorTable GROUP BY sensorID ORDER BY max(timestamp); I have seen that the group_by() function exists and also lastest() but I don't get anything coherent and I'm also not clear if I'm choosing the best form. Can anyone help me get started with this topic? I imagine it is very easy but it is a new world and it is difficult to start. Greetings! -
How to catch Timeout error before DRF raise its own Timeout?
I have external API to work with it. I have my own endpoint in DRF which should send request to external API and handle response from it before I return it to client application. This is code example: serializers.py api_integration = validated_data["form"].api_integration data = dict() for field in validated_data['form_fields']: data.update(field) headers = dict() headers["Authorization"] = api_integration.token headers["Content-Type"] = api_integration.content_type try: response = requests.post( api_integration.url, data=data, headers=headers ) except requests.exceptions.RequestException: return Response({"detail": "Something went wrong"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) When I am using debug console in PyCharm and set breakepoint on return Response... line all works as well, I handle 502 error from external API and return my own response, but when this code run without debug breakpoints I get 502 BadGateway from DRF. I find only 1 decision - change timeout time in my nginx settings, but for me this is not the best decision, I want to handle this Timeout error only in this endpoint. -
Django Form Validation Error Not Showing In Template
my issue is exactly as the problem states...I am unable to get form validation errors to work. I will post what I am currently trying below. Please let me know how I can amend my code in order to get this working. Currently, I can even successfully submit the form with any name. So clearly what I have set in forms.py is not even working... forms.py class PackingListForm(forms.ModelForm): class Meta: model = PackingList fields = ['Exporter', 'Consignee', 'Reference_Number', ... ] def clean_test_value(self): data = self.cleaned_data.get('Exporter') if not Exporter == 'Jeff': raise forms.ValidationError('ahhhh Error!') return data template (packlist.html) <td rowspan="3"colspan="2">Exporter: {{ form.Exporter }} {% for error in form.Exporter.errors %} <P class='help is-danger'>{{ error }}</p> {% endfor %} </td> views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): .....do stuff here...... else: return render(request, 'packlist.html', {'form': form}) else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Django ModelChoiceField initial value not working despite it is well set up
I have the following form : class UserUpdateForm(ModelForm): class Meta: model = User fields= '__all' widgets = { 'inscription_date': forms.DateInput(format=('%d-%m-%Y'), attrs={'class': 'datepicker', 'placeholder': 'Select a date'}) } def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) current_user_id = User.objects.get(id=self.instance.id).id group_name = GroupName.objects.filter( usergroup__user__id=current_user_id).get().name current_location = User.objects.filter(id=self.instance.id).values( location=F('record__location__nom')).distinct().get() self.fields['location'] = forms.ModelChoiceField( queryset=Location.objects.all(), initial=current_location['location']) def get_form(self): form = super().get_form() return form The initial value is not working. I checked and the value inside current_location['location']is correct. I tried as well to write self.initial['location'] = current_location['location'] but still not working. This is the way, I instantiate my form : @method_decorator(login_required, name='dispatch') class UserUpdateView(LoginRequiredMixin, UpdateView): model = User form_class = UserUpdateForm template_name = 'dashboard/users/user_update_form.html' def get_success_url(self): messages.success(self.request, "The user %s was updated successfully" % ( self.object.first_name)) return reverse_lazy('dashboard:users') Do you have any clues ? -
How to open a document present in EC2 server in local machine?
I deployed my Django Project in AWS EC2 server. My website got hosted successfully. Iam running a python code on click of a HTML button to open am Excel Sheet. Python code to open the excel sheet is given below: import webbrowser a_website = "C:\python\Python38\result.xlsx" webbrowser.open_new(a_website) The excel sheet is opening in the EC2 server. But I need Excel sheet to be displayed in my local machine on which Iam clicking the HTML button on the hosted Website. How will I open the Excel sheet present on EC2 server in my local machine? -
django.db.utils.OperationalError: FATAL: password authentication failed for user "hello_django"
Background I'm halfway through a tutorial on setting up Django with Docker. My problem When I try to migrate the postgresql database using the followiing command: docker-compose exec web python manage.py migrate --noinput I get the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "hello_django" My setup: Settings.py: DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } .env.dev: DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=hello_django_dev SQL_USER=hello_django SQL_PASSWORD=hello_django SQL_HOST=db SQL_PORT=5432 Dockerfile: FROM python:3.7.0-alpine WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ Docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./myproject/.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev volumes: postgres_data: Can somebody point me in the right direction? -
Django Forms Validations
Suppose I've a form for creating new user. and In the django view I'm handling data somethings like this. username = request.POST.get('username') .......... .......... Now here I've a problem that how to validate and save data into the model. By the way this is not a actual case... -
PATCH (partial=true) doesn't work in Django
I have a PATCH endpoint to change some non required data for a "Site". Through the endpoint you should be able to edit the description and supplier from a Site. The description is already working on the existing project. When I try to add the supplier to the PATCH, it doesn't update it.. View: class AdminSiteDetailView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), def get_serializer_class(self): return AdminSiteDetailSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully"), AdminSiteDetailSerializer, ) } ) def get(self, request, site_pk): """ GET the data from the site. """ #somecode @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully"), AdminSiteDetailSerializer, ) } ) def patch(self, request, site_pk): """ PATCH the description of the site. """ site = get_object_or_404(Site, pk=site_pk) serializer_class = self.get_serializer_class() serializer = serializer_class(site, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() site.save() return Response(serializer.data, status=status.HTTP_200_OK) Serializer: class AdminSiteSerializer(serializers.ModelSerializer): supplier = serializers.SerializerMethodField() class Meta: model = Site fields = [ "id", "name", "supplier", ] @staticmethod def get_supplier(site): if not site.supplier: return None return SupplierSerializer(site.supplier).data class AdminSiteDetailSerializer(AdminSiteSerializer): class Meta(AdminSiteSerializer.Meta): fields = AdminSiteSerializer.Meta.fields + ["description"] class SupplierSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ("id", "name") model: class Site(models.Model): class Meta: ordering = ("name",) name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) supplier = models.ForeignKey( Supplier, on_delete=SET_NULL, blank=True, null=True, related_name="sites" ) -
Correct way to delete all MpttModel Entries using Django Manager
I have a Django model(Feature) sub-classing MPTTModel. As best practice for MPTT model for foreign key is to keep on_delete=PROTECT, struggling to delete all MPTT entries at once, using Feature.objects.all().delete() I can either first delete all child nodes, and then root nodes. But this does not seem efficient to me. Is there any better option ? -
Displaying ppt and word documents on Django Templates
I am working on an e-learning website that has 3 portals; Admin Teacher and Student. The Course materials are uploaded by Admin and viewed by Students. I have displayed the file using iframe. If the file is PDF, it is getting displayed within iframe, but PPT and DOC files are getting downloaded automatically. Can someone help me with how to display PPT and Doc files within Iframe? -
from django.conf import settings NOT loading dev settings
My settings are structured like: /settings/init.py /settings/base.py /settings/dev.py /settings/prod.py The constant RANDOM_VAR is set in dev.py When I do the following in e.g. urls.py from django.conf import settings print(settings.RANDOM_VAR) I get AttributeError: 'Settings' object has no attribute 'RANDOM_VAR' After further testing I see that all my database settings etc. are loaded from dev.py. But when I want to access my dev.py settings through from django.conf import settings it doesn't work. Any ideas? -
How to get selected value in dropdown list, then pass it to views.py
I'm working on an upload file feature with dropdown and dropzone. But, whenever I submit the uploaded file with selected option, it always says that the selected option is None. I found it None after I printed the nama_bimbingan in views.py. Here it is my code. url.py .... url(r'bimbingan/add/upload', mengelola_bimbingan.upload_data_bimbingan, name='add-bimbingan-excel'), url(r'bimbingan/download-template/', mengelola_bimbingan.bimbingan_template, name='bimbingan-template'), .... forms.py class UploadBimbinganForm(forms.Form): ... ... dropdown_choices = tuple(zip(all_pembimbing, all_pembimbing)) nama_pembimbing = forms.ChoiceField(choices = dropdown_choices) upload_bimbingan.html <form method="POST" action="{% url 'app:add-bimbingan-excel' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="py-3"> <label for="id_nama_pembimbing"> Nama Pembimbing Akademik: </label> <select class="form-control mb-2" id="id_nama_pembimbing" name="nama_pembimbing" required> <option value = "" selected="selected">---------</option> <option value = {{form.nama_pembimbing}}></option> </select> </div> <div id="myDropzone" class="dropzone" drop-zone> <h6 class="dz-message"> Drop file here or click to upload</h6> </div> <div class="py-3"> <a href="{% url 'app:bimbingan-template' %}">Download Template</a><br> <div class="row justify-content-between py-3"> <div class="col-md-5 mb-1"> <a href="{% url 'app:read-all-bimbingan' %}" class="btn btn-blue-outlined">Batal</a </div> <div class="col-md-5"> <input type="submit" value="Simpan" class="btn btn-block btn-blue"> </div> </div> </div> </form> views.py @login_required(redirect_field_name='index') @user_passes_test(only_admin_access) def upload_data_bimbingan(request): form = UploadBimbinganForm(request.POST or None) if request.method == "POST" and 'file' in request.FILES: nama_pembimbing = request.POST.get('nama_pembimbing') excel_file = request.FILES["file"] data = get_data(excel_file, column_limit=1) bimbingans = data["Bimbingan"] ... ... if(len(duplicate) == 0): space_parsed_query = nama_pembimbing.replace(' ', '%20') cleaned_query = space_parsed_query.replace(',', '%2C') nip_pembimbing … -
ModuleNotFoundError: No module named error when starting Django shell
When running 'python manage.py shell', I'm getting the following message: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Anaconda3\envs\mysite\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "D:\Anaconda3\envs\mysite\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "D:\Anaconda3\envs\mysite\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package I have tryed another solution where I had to use ./manage.py shell --plain, but this didn't work. Also tryed a solution that stated the ipython version wasn't correct, but that solution didn't solve anything for me either. -
Squash migrations in Django
I'm quite new to Django, I have some 30 migration files and squashed last 6 migration files into 1 migration file. Now that I have squashed migrations into one file, can I delete the old 6 migration files? -
django form is not valid but validation not working
When I submit form it doesn't show any validation error and form is not valid views.py def institute(request): context = {} if request.POST and request.FILES: form = InstituteForm(request.POST, request.FILES) context['form'] = form if form.is_valid(): form.save() messages.add_message( request, messages.SUCCESS, "Successfully Added Institute Information") return redirect('accounts:profile') else: context['form'] = InstituteForm() return render(request, 'institute.html',context) according to forms.py it should return email or phone validation error but there is no errors in template and form data is saving in database forms.py class InstituteForm(forms.ModelForm): class Meta: model = Institute fields = '__all__' exclude = ('create', 'update', 'admin') def clean_phone(self): phone = self.cleaned_data['phone'] emp = Employee.objects.filter(phone=phone).count() ins = Institute.objects.filter(phone=phone).count() if emp > 0 or ins: raise ValidationError('This Phone Number is already used, try new one') return phone def clean_email(self): email = self.cleaned_data.get('email') emp = Employee.objects.filter(email=email).count() ins = Institute.objects.filter(email=email).count() if ins > 0 or emp: raise ValidationError('This email is already used, try new one') return email -
django NOT NULL constraint failed: " ............... "
I'm new in django and I want to ask you the following question. I have two models: monthly income, that rappresents my single item monthly income and total montly income, that rappresent the summ of all items monthly income. My models.py is the following: from django.db import models from djmoney.models.fields import MoneyField class Vendite(models.Model): ricavi_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_dalle_vendite_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_dalle_vendite_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) class Totale_Vendite(models.Model): ricavi_tot_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) My views is the following: def ricavi_dalle_vendite(request): items = Vendite.objects.all() if request.method == 'POST': form = VenditeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = VenditeModelForm() data_jan = list(Vendite.objects.aggregate(Sum('ricavi_dalle_vendite_01')).values())[0] data_feb = list(Vendite.objects.aggregate(Sum('ricavi_dalle_vendite_02')).values())[0] jan = data_jan feb = data_feb total_income = Totale_Vendite(ricavi_01=jan, ricavi_02=feb, id=1) total_income = Totale_Vendite(ricavi_01=jan, ricavi_02=feb, id=1) total_income.save() context= { "form": form, 'items': items, } return render(request, "app/vendite.html", context) The code works well, but when I'm going to delete the first items inserted in the models "Vendite" django give me the error NOT NULL constraint failed: app_totale_vendite.ricavi_01. I think that the error is about my constraints "id=1" in my views, but I need to have in Totale_vendite model only a row, that update itself … -
How do I store multiple values in a single variable or list in django views.py?
Here is my views.py @login_required def appsc(request): allapplied = Applied_Scholarships.objects.filter(user_id = request.user.id) for applied in allapplied.iterator(): print('hi') sch_id = applied.scholarship_id queryset = ScholarshipDetails.objects.filter(id = sch_id) print(queryset) context = {"object_list":queryset} return render(request,'applied-scholarships.html',context) Here, I need to check the applied scholarships of a student. So for that, I have filtered the entries from the Applied_Scholarship table. Now from that, I took scholarship_id and filtered the entries in ScholarshipDetails table so that I get the name and other details of the scholarship. Now how do I prevent object_list to get overridden? This code gives me value of only 1 scholarship instead of 2. Here is my template: <table class="table mb-0"> <tr> <th>Scholarship name</th> <th>End Date</th> <th>Status</th> <th></th> <th></th> </tr> {% for instance in object_list %} <tr> <td>{{instance.name}}</td> <td>{{instance.end_date}}</td> <td>{{applied.status}}</td> <td><a href = "government/home">{{schdets.link}}</a></td> </tr> {% endfor %} </table> Do I need to use list? If yes, then how? -
Django TruncDate gives null
I'm using Django 2.2 I'm filtering records using Django query like from datetime import datetime from django.db.models.functions import TruncDate start_date = datetime.strptime('2020-02-01', '%Y-%m-%d').date() end_date = datetime.strptime('2020-03-31', '%Y-%m-%d').date() lead_list = LeadList.objects.all() # Filter query query = LeadListEntry.objects.filter( lead_list__in=lead_list ) # Filter by start date query = query.filter( created__gte=start_date ) # Filter by end date query = query.filter( created__lte=end_date ) # Annotate date query = query.annotate( created_date=TruncDate('created') ).order_by( 'created_date' ).values('created_date').annotate( **{'total': Count('created')} ) The SQL query generated is SELECT DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC')) AS `created_date`, COUNT(`lead_generation_leadlistentry`.`created`) AS `total` FROM `lead_generation_leadlistentry` WHERE ( `lead_generation_leadlistentry`.`lead_list_id` IN ( SELECT U0.`id` FROM `lead_generation_leadlist` U0 WHERE U0.`deleted` IS NULL ) AND `lead_generation_leadlistentry`.`created` >= '2020-02-01 00:00:00' AND `lead_generation_leadlistentry`.`created` <= '2020-03-31 00:00:00' ) GROUP BY DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC')) ORDER BY `created_date` ASC This is behaving different on local and staging server Local Development server +--------------+-------+ | created_date | total | | ------------ | ----- | | 2020-02-25 | 15 | | 2020-02-27 | 10 | +--------------+-------+ Staging server +--------------+-------+ | created_date | total | | ------------ | ----- | | null | 15 | +--------------+-------+ The date column is null NOTE: Django has timezone enabled by USE_TZ=True -
Django: How to make model attribute dependent on foreign key present in that model
I have two models in Django : State and City class State(models.Model): #regex = re.compile(r'^[a-zA-Z][a-zA-Z ]+[a-zA-Z]$', re.IGNORECASE) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100, unique=True) class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100, unique=True) postalcode = models.IntegerField(unique=True) In city model I have attribute state which is foreign key from State model. In city model I want to make attribute name dependent on state attribute, as one state will have one city with same name but one city name can be in many states. Like City Udaipur is in both Rajasthan and UttarPradesh in India, but Rajasthan will have single city as Udaipur. -
how to implement function the same as make_password, check_password without Django
I have used Django and handled password with make_password and check_password. however, I get to change a framework to another (other than Django). With another framework, I need to verify passwords that are created by Django because I should use the same database with the data. How to encrypt(make_password) and verify(check_password) the same as Django did without Django? I think it is possible to implement the function like Django's one if I know the internal logic. Password's format stored in database is like that 'pbkdf2_sha256$100000$Dl6Atsc1xX0A$0QFvZLpKdcvcmCNixVCdEA5gJ67yef/gkgaCKTYzoo4=' -
Django duplicate migrations in apps
Django keeps making duplicate migrations in for my application. I've ran makemigrations and migrate before I changed my model. After the changes I ran makemigrations again to make migrations for the updated model, I got the following error: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0001_initial 3 in sessions; 0002_remove_content_type_name 3, 0002_remove_content_type_name, 0001_initial 3 in contenttypes; 0002_alter_permission_name_max_length 3, 0010_alter_group_name_max_length 3, 0007_alter_validators_add_error_messages 3, 0006_require_contenttypes_0002 3, 0005_alter_user_last_login_null 3, 0001_initial 3, 0008_alter_user_username_max_length 3, 0009_alter_user_last_name_max_length 3, 0011_update_proxy_permissions, 0011_update_proxy_permissions 3, 0004_alter_user_username_opts 3, 0003_alter_user_email_max_length 3 in auth; 0003_logentry_add_action_flag_choices 3, 0002_logentry_remove_auto_add 3, 0003_logentry_add_action_flag_choices, 0001_initial 3 in admin). To fix them run 'python manage.py makemigrations --merge' Running makemigrations --merge doesn't work: ValueError: Could not find common ancestor of {'0002_remove_content_type_name', '0002_remove_content_type_name 3', '0001_initial 3'} There are many duplicate migrations in apps that I haven't touched (auth, admin, etc.): admin [ ] 0001_initial 3 [X] 0001_initial [ ] 0002_logentry_remove_auto_add 3 [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices [ ] 0003_logentry_add_action_flag_choices 3 auth [ ] 0001_initial 3 [X] 0001_initial [ ] 0002_alter_permission_name_max_length 3 [X] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length 3 [X] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts 3 [X] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null 3 [X] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 3 [X] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages 3 [X] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length 3 … -
How can I go to specific url from template in django?
I have bunch of urls in urls.py , and In template I have defined like below : <li><a href="{% url 'vieweinvoices' %}">Billing</a></li> <li><a href="{% url 'proformainvoice' %}">Proforma Invoice</a></li> <li><a href="{% url 'viewequotations' %}">Quotation</a></li> But the problem is if I click on one line say viewinvoices, and after that I click on proformainvoice, it redirects to localhost:8000/vieweinvoices/proformainvoice.html but it should go to localhost:8000/proformainvoice.html how can I do that? -
return data from json file if another one is not exist
i'm trying to return data to django model, from Overpass API json data after downloaded "elements": [ { "type": "node", "id": 662934404, "lat": 35.572157, "lon": 45.3898839, "tags": { "addr:postcode": "46001", "name": "City Center", "name:en": "City Center Mall", "name:ku": "City Center Mall", "shop": "mall", "website": "http://www.citycentersul.com" } }, { "type": "node", "id": 2413990402, "lat": 35.5014386, "lon": 45.4457576, "tags": { "addr:city": "sulaymaniyah", "designation": "ASSAN", "name": "ASSAN STEEL CO.", "opening_hours": "3 min", "shop": "doityourself", "source": "ASSAN Steel Company General Trading Co, Ltd" }, { "type": "node", "id": 2414374708, "lat": 35.506121, "lon": 45.4417229, "tags": { "addr:city": "sulaymaniyah", "name:ku": "ASSAN Steel Company General Trading Co, Ltd", "shop": "doityourself", } }, but some of the data dosent have both of them together name , name:ku ,name:en so what should i do if name is none then return name:ku , if its exists then name:en i've tried this but doesnt work with open('data.json') as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType = obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name') if not name: name = tags.get('name:en') elif not name: name = tags.get('name:ku') elif not name: name = tags.get('name:ar') else: name = tags.get('shop','no-name') is there something else i've missed ? thanks for … -
Django - First call to reverse is slow
I have to call several times Django reverse method in order to return several urls to the client. The first reverse call takes between 1 and 2 seconds while all the following, even with different routes are very fast. What exactly is happening with the first one ? Is there a way to speed this up ?