Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to importing python class in django case
why we import like this. from django.db.models import Model, Model class is inside base.py not models. expecting from django.db.models.base import Model, why base module ommitted. django/db/models/base.py is the structure -
How to deploy Django Webapp with subdomain
I have a domain as abc.com. I have created subdomain as xyz.abc.com. I have two Django Webapps both are not same. I want to deploy both Django Webapps with this domain and sub-domain on same VPS server. Webapp deployed on main domain works very well. But when I try to do same thing with wepapp and sub-domain it shows error as Not Found. I am using apache2 server to deploy webapp. Here is my apache configuration. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName xyz.abc.com ServerAlias www.xyz.abc.com DocumentRoot /home/altaf/LinkSuggestion/LinkSuggestion Alias /static /home/altaf/LinkSuggestion/LinkSuggestion/static <Directory /home/altaf/LinkSuggestion/LinkSuggestion/static> Require all granted </Directory> <Directory /home/altaf/LinkSuggestion/LinkSuggestion/LinkSuggestion> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess linksuggestion python-path=/home/altaf/LinkSuggestion/LinkSuggestion python-home=/home/altaf/LinkSuggestion/envlinksuggestion WSGIProcessGroup linksuggestion WSGIScriptAlias / /home/altaf/LinkSuggestion/LinkSuggestion/LinkSuggestion/wsgi.py ErrorLog ${APACHE_LOG_DIR}/linksuggestion_error.log CustomLog ${APACHE_LOG_DIR}/linksuggestion_access.log combined </VirtualHost> It shows error as : **Not Found** The requested resource was not found on this server. -
Why won't my home page redirect to a detail view (Django)
So the context is I'm following a tutorial on codemy.com. Somewhere before Django 5.0 I lost my "magic", the tutorial was written for 3.8 or 4.X maybe. I am showing a function based view although I have tried the class base view as suggested on the codemy youtube. The reason I chose function view is it was easier for me to debug. views.py from django.shortcuts import render from django.views.generic import ListView #DetailView from django.http import HttpResponse from .models import Post class Home(ListView): model = Post template_name = "home.html" def articleDetail(request, pk): try: obj = Post.objects.get(pk=pk) return render(request, "article_detail.html", {object, obj}) except Post.DoesNotExist: print("Object number: " + str(pk) + " not found") return HttpResponse("Object number: " + str(pk) + " not found") the model from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return str(self.title) + ' by: ' + str(self.author) the urls file from django.urls import path,include from .views import Home, articleDetail urlpatterns = [ path('', Home.as_view(), name="home"), path('article/<int:pk>', articleDetail,name="article-detail"), ] the template for home, works fine until redirect <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Landing!!!</title> <h1> Home Pageeeeee</h1> </head> <body> <ul> <h2>Articles</h2> {% for article … -
Djang rest frame-work error : django.core.exceptions.ImproperlyConfigured: Router with basename X is already registered , despite it is not
In my django app am using DRF and it gives me , and it gives me this strange error when i try to run the app : water_maps | router.register(r'breaches_edit_delete', api.BreacEditDeletehViewSet) water_maps | File "/usr/local/lib/python3.10/dist-packages/rest_framework/routers.py", line 59, in register water_maps | raise ImproperlyConfigured(msg) water_maps | django.core.exceptions.ImproperlyConfigured: Router with basename "breach" is already registered. Please provide a unique basename for viewset "<class 'water_maps_dashboard.api.BreacEditDeletehViewSet'>" despite there is no duplication and the routers ,, here is my URLS file : from django.urls import path, include from rest_framework import routers from . import api from . import views from .api import check_current_version, check_for_device_id, check_for_login, get_cords_ids router = routers.DefaultRouter() router.register("main_depart", api.MainDepartmentViewSet) router.register("job_description", api.JobDescriptionViewSet) # router.register("section", api.SectionViewSet) router.register("city", api.CityViewSet) router.register("AppUser", api.AppUserViewSet) router.register("Breach", api.BreachViewSet) router.register("Section", api.SectionViewSet) router.register("MapLayers", api.MapLayersViewSet) router.register("LayersCategory", api.LayersCategoryViewSet) router.register("UserMessage", api.UserMessageViewSet) router.register("about_us", api.AboutUsViewSet) # router.register(r'breaches_edit_delete', api.BreacEditDeletehViewSet) router.register(r'edit_delete_breach', api.BreacEditDeletehViewSet) urlpatterns = ( path("api/do_search/", api.do_search, name="do_search"), path("api/activate_account/", api.activate_account, name="activate_account"), path("api/user_login/", api.user_login, name="user_login"), path("api/create_app_user/", api.create_app_user, name="create_app_user"), path("api/save_breaches/", api.save_breaches, name="save_breaches"), path("api/add_cords_to_breach/", api.add_cords_to_breach, name="add_cords_to_breach"), path("api/do_forgot_password/", api.do_forgot_password, name="do_forgot_password"), path("api/reset_password/", api.reset_password, name="reset_password"), path("api/get_my_breaches/", api.get_my_breaches, name="get_my_breaches"), path("api/map_view/", api.map_view, name="map_view"), path("api/post_user_message/", api.post_user_message, name="post_user_message"), path("api/add_edit_request/", api.add_edit_request, name="add_edit_request"), path("api/request_delete_account/", api.request_delete_account, name="request_delete_account"), path("api/", include(router.urls)), path("api/check_for_login/", check_for_login, name="check_for_login"), path("api/check_for_device_id/", check_for_device_id, name="check_for_device_id"), path("api/check_current_version/", check_current_version, name="check_current_version"), path("api/get_cords_ids/", get_cords_ids, name="get_cords_ids"), path("upload_data/", views.upload_data, name="upload_data"), path("admin_logs/", views.admin_logs, name="admin_logs"), path("trigger_task/", views.admin_logs, name="trigger_task"), path("send_email/", views.send_email_to_users, name="send_email"), … -
composite primary key django and timescaledb (postgresql)
I am using django for my backend and postgresql for my database cause I have timeseries data i use timescaledb. i have hypertable called devices. there is a composite primary key on fields created_datetime(timestamp) and device_id(integer). I want to use django built in logging users activities ( LogEntry table), so i should have a model representing the hyper table . how can I do this? I have tried so many things like creating a model putting created_datetime as primarykey then in adminsite i had error ID “2024-05-06 11:55:21” doesn’t exist. Perhaps it was deleted? -
how to integrate QR code payment in django
I am facing the issue to integrate QR code in python django website but not getting proper solution Please help me that how can i integrate the QR code payment gateway in django. and what will be the payment method best for this? -
Django products not being added to cart immediately
So I am trying to build a Django e-commerce website, where there is a cart modal which pops up when I try to add any product by clicking the add to cart button. While the product is being added correctly in the backend (which I can verify by going to admin panel), the product just doesn't show up immediately on my cart modal, something which is essential for the website to look good. Only when I am refreshing the page, the product shows up on my modal. Been stuck on this for the last 3 days, no clue what to do. Can someone please help me out here? Thanks! My cart model: class Cart(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='cart') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username} - {self.product.name}" My views.py: class CartView(LoginRequiredMixin, View): def get(self, request): cart_items = Cart.objects.filter(user=request.user) total_price = sum(item.product.price * item.quantity for item in cart_items) return render(request, 'business/cart.html', {'cart_items': cart_items, 'total_price': total_price}) def post(self, request): try: data = json.loads(request.body) product_id = data.get('product_id') except json.JSONDecodeError: logger.error("Invalid JSON data in the request body") return JsonResponse({'error': 'Invalid JSON data'}, status=400) logger.debug(f'Received product_id: {product_id}') if not product_id: logger.error("No product_id provided in … -
Streaming LLM output in Django
Im planning to develop Django framework for the LLM fine-tuned model based on HuggingFace models, I want the text to be streamed from model to the Django. My issue is that model streams the output in the terminal but not sure how to make it in a stream in a variable so that I can transfer it to the end-user I tried using pipeline with TextStream but it only output the text in the terminal model_id = "model_a" model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True, # attn_implementation="flash_attention_2" ) tokenizer = AutoTokenizer.from_pretrained( model_id, trust_remote_code=True ) streamer = TextStreamer(tokenizer) pipeline = pipeline( "text-generation", model=model, tokenizer=tokenizer, model_kwargs={"torch_dtype": torch.bfloat16}, streamer=streamer ) -
Why no pip packages accessible from any new directory wheras it is accessible from existing directories while in venv
I am working on a Django project. Recently while working on my new project, I had to delete py an open project folder. Now I am not able to access the list of pip packages from any of the newly created directories except being shown pip version number when I activate venv. However the pip list is accessible from any of the previously created directories even if create a venv in that foldeer and activate that venv. My file directory structures are as given below: pip list accessible in records_log folder of the following directory: C:\Users\abc\Projects\Python_proj_1\Python_proj_ml\records_log pip list is not accessible in newly created sub directory projects_practice folder: C:\Users\abc\Projects\Python_proj_1\Python_proj_ml\projects_practice\records_log The mini conda is installed at the following location: C:\Users\abc\miniconda3 I am able to mitigate this issue by changing the following line in pyvenv.cfg to True, which is supposed to remain default remains 'false' in all normally working directories. include-system-site-packages = true But as I know that there is something amiss. I do not wish to resort to using this work around like the one mentioned above. I need help to fix this issue and get the system as it was before I deleted the project file which led to this … -
Django form with MediumEditor not honoring required attribute
In Django, I have a TextField called 'description' in a model with null and blank set to False (for server side and client side validation). I'm using forms.ModelForm to pull the field and I'm using forms.Textarea to assign attributes. In the attributes, I'm assigning the medium-editor-textarea class attribute to leverage MediumEditor. This field is working as intended and the MediumEditor js is indeed called so that a user can leverage the MediumEditor wysiwyg in the text area; I also have a script in my form template that initializes a new instance of the MediumEditor class with all elements that have the class 'editable': var editor = new MediumEditor('.editable');. The one problem I'm having is that while the div and textarea both contain the required attribute, this is not prompting on the client side that this field is required when a user submits the form. Rather, I continually get the following error message in the console: An invalid from control with name='description' is not focusable, and this points to the textarea tag. In short, even with the required attributes, the browser prompt that the field cannot be empty is not firing on the client side. Here is the relevant code, trimmed … -
Trying to integrate TinyMCE into django but TinyMCE editor is not showing up
I'm following along sentdex's django development tutorial. This is the code in the admin.py file class TutorialAdmin(admin.ModelAdmin): fieldsets = [ ("Title/date", {"fields": ["tutorial_title", "tutorial_published"]}), ("Content", {"fields": ["tutorial_content"]}) ] formfield_overrides = { models.TextField: {'widget': TinyMCE()} } admin.site.register(Tutorial, TutorialAdmin) the tinyMCE editor is not showing up in the site I tried to add TinyMCE to a django site, but it is not showing up. How do I get TinyMCE to show up? -
Django rest framework's ModelSerializer missing user_id field causing KeyError
My ModelSerializer is getting a KeyError when I call .data on the serializer and I'm not sure how to properly fix this error. Knox's AuthToken model looks like this class AuthToken(models.Model): objects = AuthTokenManager() digest = models.CharField( max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True) token_key = models.CharField( max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True) user = models.ForeignKey(User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(null=True, blank=True) def __str__(self): return '%s : %s' % (self.digest, self.user) I created a Model serializer class AuthTokenResponseSerializer(serializers.ModelSerializer): class Meta: model = AuthToken fields = "__all__" However, when I create a token_serializer, I get this error >> token_serializer.data *** KeyError: "Got KeyError when attempting to get a value for field `user` on serializer `AuthTokenResponseSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'user'." I think I am getting this error because when the token_serializer is created, it's missing a user key. I can see there is a user_id key but not user (Pdb) token_serializer AuthTokenResponseSerializer(context={'request': <rest_framework.request.Request: POST '/auth/token/'>}, data={'_state': <django.db.models.base.ModelState object>, 'digest': '6b82ac8776113db376d8938a641c3ebdea573b4ab49cb648c171fccc7f4a517e6450cebb21682e26f36562cf7b659f5089957ba49e99c096ebc9eaaa93ab0e53', 'token_key': '872832f8', 'user_id': 34, 'created': None, 'expiry': datetime.datetime(2024, 5, 11, 9, 17, 2, 540546, tzinfo=datetime.timezone.utc)}, partial=True): digest = CharField(max_length=128, validators=[<UniqueValidator(queryset=AuthToken.objects.all())>]) token_key = CharField(max_length=8) created = DateTimeField(read_only=True) expiry = DateTimeField(allow_null=True, … -
Optimizing Django/Postgres Query Performance: Filtering Many to Many relationship using Count Slows Down with Large Dataset
I do have such a model with class RecipeTag(models.Model): tag = models.CharField(max_length=300, blank=True, null=True, default=None, db_index=True) recipes = models.ManyToManyField(Recipe, blank=True) description = models.TextField(blank=True, null=True, default=None) language_code = models.CharField( max_length=5, choices=[(lang[0], lang[1]) for lang in settings.LANGUAGES], default='en', db_index=True # Index added here ) slug = models.CharField(max_length=300, blank=True, null=True, default=None, db_index=True) # Index added here is_visible = models.BooleanField(blank=True, null=True, default=True, db_index=True) # Index added here def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.tag) super(NewRecipeTag, self).save(*args, **kwargs) def __str__(self): tag = self.tag if self.tag else "Tag" return f"{tag} - Visible - {self.is_visible}" I need to filter all RecipeTag that have more then 2 recipes assigned to them, that I am currently doing like that tags = NewRecipeTag.objects.filter(language_code=meta['language'], is_visible=True).annotate(num_recipes=Count('recipes')).filter(num_recipes__gte=2) After that I am paginating them like that and displaying inside my html paginator = Paginator(recipe_tags, 60) page = paginator.page(page_number) recipe_tags = page.object_list My problem that, query taking around 20 seconds to finish, without annotate it happen almost instantly, I do have 4391166 records and hopping to find a solution that will help me to achieve my goal of displaying paginated tags filtered by recipes count as fast as possible, StackOverflow community that's your time! -
Django - Editing/updating records on formset triggering duplicate error
In Django, I have this FBV that updates selected records: def edit_selected_accountsplan(request): selected_items_str = request.GET.get('items', '') selected_items = [int(item) for item in selected_items_str.split(',') if item.isdigit()] accountsplan_to_edit = AccountsPlan.objects.filter(id__in=selected_items) AccountsPlanFormSet = formset_factory(form=AccountsPlanForm, extra=0) if request.method == 'POST': formset = AccountsPlanFormSet(request.POST) if formset.is_valid(): for form, accountplan in zip(formset, accountsplan_to_edit): accountplan.subgroup = form.cleaned_data['subgroup'] accountplan.name = form.cleaned_data['name'] accountplan.active = form.cleaned_data['active'] accountplan.save() return redirect('confi:list_accountsplan') else: initial_data = [] for accountplan in accountsplan_to_edit: initial_data.append({ 'subgroup': accountplan.subgroup, 'name': accountplan.name, 'active': accountplan.active, }) formset = AccountsPlanFormSet(initial=initial_data) return render(request, 'confi/pages/accountsplan/edit_selected_accountsplan.html', context={ 'formset': formset, }) Everything works as expected (the page loads, the form is filled correctly etc.) except when saving the data. The 'name' field is defined as unique in the database, so when I try to change other fields but don't change the name, it gives me a duplicate error. If I change the name to anything else that is not already in the database, it updates the current name correctly, so it's not creating a new record. I've tried to change the loop block to this just to see if I could save: for form, accountplan in zip(formset, accountsplan_to_edit): form.instance = accountplan form.save() return redirect('confi:list_accountsplan') But again, the duplicate error is triggered. I don't understand why this … -
Getting ModuleNotFoundError: No module named 'django' while deploying Django on uWSGI server, while uWSGI server is running on Cygwin on Windows OS
I have installed Cygwin on Windows 10 and installed following packages gcc-core (version 11.0.4-1, under Devel category ) gcc-g++ (version 11.0.4-1, under Devel category ) libintl-devel (version 0.22.4-1, under Text category ) gettext-devel (version 0.22.4-1, under Text category ) python3-devel (version 3.9.16-1, under Python category ) python38-devel (version 3.9.16-1, under Python category ) And I have installed uWSGI version 2.0.25.1 in Cygwin, to deploy a django application. The wsgi.py file of the Django application looks like import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PrateekGupta.settings') application = get_wsgi_application() The config file for uWSGI looks like [uwsgi] chdir = P:/Portfolio/Django module = PrateekGupta.wsgi:application pythonpath = /home/PrateekGupta/virtual_environment/Scripts/python master = True pidfile = /tmp/project-master.pid vacuum = True max-requests = 5000 daemonize = /var/log/Portfolio.log http-socket = 127.0.0.1:8000 buffer-size = 65536 I have activated the Virtual Environment and have installed python and django in it. The response of the pip list command is Package Version ----------------- ------- asgiref 3.8.1 Django 5.0.6 pillow 10.3.0 pip 21.3.1 PyJWT 2.8.0 setuptools 58.4.0 sqlparse 0.5.0 typing_extensions 4.11.0 tzdata 2024.1 wheel 0.37.0 But still whenever I run the uwsgi server with the command uwsgi --ini portfolio-uwsgi.ini In the log file I'm getting the error Traceback (most recent call last): File "/cygdrive/p/Portfolio/Django/./PrateekGupta/wsgi.py", … -
Quelle est le meilleur programmation pour une plateforme de protection de données [closed]
je suis sur le point de réaliser une plateforme de protection et je demande la plus adéquate programmation pour réaliser ce plateforme je ne suis qu'au tout début qui est le cahier de charge et le plan mais je saiqs la programmation utiliser Django python PHP java -
Static files path generated incorrectly in Django project
Description: In my Django project, the static files path is generated incorrectly, appending the current page URL before the static URL. For example, when I'm on the about page, the path becomes http://127.0.0.1:8000/about/static/images/bg/17.jpg instead of http://127.0.0.1:8000/static/images/bg/17.jpg. This causes issues with serving static files. How can I debug and fix this issue? STATIC_URL = '/static/' #Location of static files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've checked my settings.py file and ensured that STATIC_URL = '/static/'. My static files are located in the correct directory (static/images/bg/17.jpg). I'm using the {% static %} template tag in my templates to reference static files. I've also run collectstatic after making changes to my static files. Expected Behavior: I expect the static files path to be generated as http://127.0.0.1:8000/static/images/bg/17.jpg regardless of the current page URL. -
Nginx + React + Django: Understanding CORS Request Headers
I'm hosting a React frontend app and Django backend API on Nginx in a single local Raspberry Pi, on ports 80 and 8000, respectively, with the following config: // REACT APP server { listen 80; listen [::]:80; root /link-to/build; index index.html; server_name pinode; location / { try_files $uri /index.html; } } // Django APP/Gunicorn server { listen 8000; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /link-to/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } For my use case, I'd like all internal requests between react and django to use localhost. However, the user can access the react front end using the Raspberry Pi's hostname (in this case, http://pinode/ as seen in nginx config above). In react, all API calls use http://localhost:8000/api/*. During my testing of the above, I had some level of success. However, one of the following always fails exclusively: During login, I get a response from http://localhost:8000/api/login/, but the Set-Cookie fails due to Cross-Site policy. Attempting to add headers to nginx backend config results in requests being rejected due to CORS policy. Post requests are rejected due to a missing csrftoken, despite axios is setup with X-CSRFToken header … -
How to post image and text in React Js form?
Here i have two component Child Component which passes text and image to the Parent component and Parent post the form But text is passed but image is getting error. I am using Django as Backend I can provide it too if required. Its just a simple Django-Rest-Framework No validation. Here when i console.log() p_details.Banner, p_imgs.Image both are providing an File Though i am facing Error. Banner : ['The submitted data was not a file. Check the encoding type on the form.'] product_image :"Image": [ "No file was submitted." ] const Parent_Comp = ({p_details, p_imgs}) =>{ const handleSubmit = async (event) => { event.preventDefault(); const products = new FormData(); Object.keys(p_details).forEach((key) => products.append(key, p_details[key])); var parentObj = []; for (var key in p_imgs.Image) { if (p_imgs.Image.hasOwnProperty(key)) { var file = p_imgs.Image[key]; var nameWithKey = p_imgs.Name + "[" + key + "]"; var obj = { "Name": nameWithKey, "image": file }; parentObj.push(obj); } } products.append('product_image', JSON.stringify(parentObj)); const productsObj = {}; for (const [key, value] of products.entries()) { if (key === 'product_image') { productsObj[key] = JSON.parse(value); } else { productsObj[key] = value; } } console.log(productsObj); try { const res = await axios.post('http://127.0.0.1:8000/media/product/create/', productsObj, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', // Assuming you're … -
Forbidden (CSRF cookie not set.) when trying to connect from a desktop app
I'm developing a desktop application where users can log in using credentials from my Django website's database. The goal is for users to be able to create posts on the Django website (forum) through the desktop application. In the desktop app's code, I have the following code, which successfully retrieves a CSRF token from Django: def get_csrf_token(): # Make a GET request to your Django server to fetch the CSRF token response = requests.get('http://127.0.0.1:8000/accounts/get-csrf-token/') # Check if the request was successful (status code 200) if response.status_code == 200: # Extract the CSRF token from the response JSON csrf_token = response.json().get('csrf_token') print("CSRF TOKEN: ", csrf_token) return csrf_token else: # Handle errors, such as failed requests print(f"Failed to fetch CSRF token. Status code: {response.status_code}") return None And the following code which should send the data (username, password, CSRF token) to Django: def login(self): # Retrieve username and password from input fields username = self.username_input.text() password = self.password_input.text() # Send login request to Django server url = "http://127.0.0.1:8000/accounts/login/" data = { "username": username, "password": password, } # Define the headers with the CSRF token headers = { 'X-CSRFToken': get_csrf_token() } print("x-csrftoken: ", headers['X-CSRFToken']) response = requests.post(url, data=data, headers=headers) if response.status_code == 200: # … -
Pipenv skipped update of package, Django 4.2 -> 5
I am trying to update from Django 4.2.13 to the most recent version (Django 5.0.6 at the time of writing). I ran pipenv update and a number of other dependencies were upgraded successfully, as reflected in my Pipfile.lock. However, Django was not upgraded from version 4.2.13, despite a newer version being available. Running pipienv update --outdated shows ✔ Success! Skipped Update of Package Django: 4.2.13 installed, {rdeps['required']} required (Unpinned in Pipfile), 5.0.6 available. All packages are up to date! What does this mean? How can I upgrade Django? -
Django-Oscar / Can't subscrive templates from costumer folder
I'm using django and oscar to create an ecommerce site. I'm trying to add allauth, and i need to add buttons to login_registration.html template. I set the templates dir to my custom template folder and already subscrived the oscar/base.html template and oscar/partials/brand.html template without any issue. Now i'm trying to subscrive the oscar/costumer/login_registration.html template but without any success. It simple does not go into my templates/oscar/costumer folder to look for the login_registration.html first, no matter what i do. I've tried deleting the original oscar login_registration.html to force it to look in my custom templates folder, no joy. I've tried with other html files from original oscar costumer folder, no joy. I've tried cleaning the cache, no joy. It works fine when subscriving base.html and partials/brand.html, but not inside costumer folder. -
Problem facing to fetch data from prayer time api in Django App
I am trying to fetch data from this app http://api.aladhan.com/v1/calendarByCity/:year/:month search by city but failed I am writing this code in my project. Can you please help me how to fix this problem?Thanks in advance. def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen( 'http://api.aladhan.com/v1/calendarByCity?city={Bangladesh}' + city).read() list_of_data = json.loads(source) data = { "Fajr": str(list_of_data['timings']['Fajr']), "Dhuhr": str(list_of_data['timings']['Dhuhr']), "Asr": str(list_of_data['timings']['Asr']), "Maghrib": str(list_of_data['timings']['Maghrib']), "Isha": str(list_of_data['timings']['Isha']), } print(data) else: data={} return render(request, "main/index.html",data)` I am trying to get data of five times prayer. -
Problem on django queryset and distinct/order with annotated fields
Can anybody help with this problem on django queryset distinct/order with annotated fields? THIS WORKS It returns nicely and called my Serializer after, no problem at all. def get_queryset(self) -> list: distinct_by = ('distance_to_first_point', 'id') pnt = create_point(float(lat), float(lng)) queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point") return queryset.order_by(*distinct_by).distinct(*distinct_by) THIS DOENSN'T WORK If I try to access any field on the queryset it gives me this error: Cannot resolve keyword 'distance_to_first_point' into field I'm assuming the error is due to the annotated field, but Why? Before the distinct and order I can access queryset[0].distance_to_first_point for example and it works also.. def get_queryset(self) -> list: distinct_by = ('distance_to_first_point', 'id') pnt = create_point(float(lat), float(lng)) queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point") queryset = queryset.order_by(*distinct_by).distinct(*distinct_by) queryset_ids = queryset.values_list('id', flat=True) return queryset -
What database should I use?
I am doing first steps in Django. And I want to write program which can help me in my сurrent work. What is the problem? I need to have fields with dictionary of objects. But I do not know how can I do this. As I understood it is rather problematic for sql databases. So can I use nosql ones to solve such problem?