Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to save value to model without being present on form post
I have the following Model/form/view: Model class Account(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) identifier_type = models.ForeignKey(IdentifierType, on_delete=models.SET_NULL, null=True) actflag = models.CharField(max_length=1, blank=True) created_date = models.DateTimeField(blank=True, null=True) comments = models.TextField(_( 'comments'), max_length=500, blank=True) priority_type = models.ForeignKey(PriorityType, on_delete=models.SET_NULL, null=True) deadline_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.name Form class PortfolioForm(forms.ModelForm): portfolio = forms.CharField(widget=forms.Textarea) class Meta: model = Account fields = ['name', 'comments', 'priority_type', 'deadline_date', 'identifier_type', 'portfolio'] View def portfolios(request): if request.user.is_authenticated: if request.POST: fm = PortfolioForm(request.POST) user = User.objects.get(username=request.user) if fm.is_valid(): messages.success(request, 'Portfolio has been created.') fm.save() return redirect('portfolios') else: fm = PortfolioForm() context = {"name": request.user, "form": fm} return render(request, 'portfolios.html', context) else: return redirect('login') The form works fine with posting via my template, however you will notice there are some fields within my model that are not in my form I would like to fill in automatically without the user having to fill in - for example username field I would like this to be current user that submits the form and also created_date would like the current date time the user has submitted the form. I tried to add the following to my view under if fm.is_valid(): attempting to save username as current user to the … -
Hosting Static Files on AWS - Amazon Bucket - Django
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. Thank You so much in advance. P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine. import django_heroku from pathlib import Path import os from django_quill import quill # Build paths inside the project like … -
django How do I print functions as they are called?
It's the best way I've found so far. https://pypi.org/project/Autologging/ from autologging import traced @traced class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user print(user.email) raise Exception('test') However, this method only print the decorated class. Is there any way to print all the connected subclass functions when they are called? -
How to get data from config file (config.json) in real time in settings.py file in django
I have a project made in Django. I have only added social auth for login purposes. I want selected emails only to log in to the website. I used social-auth-app-django library for social auth and added a variable SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS to the settings.py file where it contains a list of all the emails permitted for logging in. My project directory looks something like this: project_parent/ ----project/ --------settings.py --------wsgi.py --------asgi.py --------urls.py ----app/ --------models.py --------views.py --------urls.py --------admin.py ----db.sqlite3 ----manage.py ----config.json Here is the config file: { "OAUTH2": { "WHITELISTED_EMAILS": [ "xyz@gmail.com", "abc@gmail.com", "efg@gmail.com", "lmn@gmail.com" ] } } In settings.py file I have loaded the config file like this: config = open('./config.json',) data = json.load(config) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS = data['OAUTH2']['WHITELISTED_EMAILS'] I have made a webpage that takes the new mail id (need to add to the config file) and appends that particular mail id (or a list of mail ids) to the config.json file. But now the problem arises, the newly added mails don't reflect directly to the variable defined in the settings.py file. For that, I need to restart the code in order to get the latest config file. Every time I add a mail id, I need to restart the code. I thought to … -
Error NoReverseMatch at /contacto/perfil-contacto/1/
Estoy haciendo una agenda de contactos y tengo un problema a la hora de redireccionar a una url en la plantilla. Cuando quiero editar un contacto me aparece el siguiente error: NoReverseMatch at /contacto/perfil-contacto/1/ Reverse for 'actualizar_contacto' with arguments '('',)' not found. 1 pattern(s) tried: ['contacto/actualizar\-contacto/(?P[^/]+)$'] Donde el error en la plantilla es el siguiente: <a href="{% url 'contacto:actualizar_contacto' perfil.id %}"></a> La urls del archivo principal es esta: urlpatterns = [ path('admin/', admin.site.urls), path('', login_required(Inicio.as_view()), name='index'), path('contacto/', include(('MiApp.Contacto.urls','contacto'))), path('usuario/', include(('MiApp.Usuario.urls','usuario'))), path('accounts/login/', Login.as_view(), name='login'), path('logout/', login_required(logoutUsuario), name='logout'), ] Y en mi app tengo la siguiente url que corresponderia a donde quiero dirigirme, que seria la de perfil_contacto: urlpatterns = [ path('nuevo-contacto/', CrearContacto.as_view(), name='nuevo_contacto'), path('perfil-contacto/<str:pk>/', PerfilContacto.as_view() , name='perfil_contacto'), path('actualizar-contacto/<str:pk>/', ActualizarContacto.as_view() , name='actualizar_contacto'), path('eliminar-contacto/<str:pk>/', EliminarContacto.as_view(), name='eliminar_contacto'), ] Como se puede ver tiene la "pk" tanto en la url como en la plantilla. Si me pueden ayudar lo agradeceria, gracias. -
I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered
view.py def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) context = {'wallpaper': wallpaper} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) wallpaper model class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) HTML <ul> <li>{{wallpaper.name}}</li> {% for i in wallpaper.tags_set.all %} <li>{{i.tags}}</li> {% endfor %} url.py path('<wallpaper_name>/', views.download, name="download"), Like example the wallpaper I have choosen to download has tags nature and ocean so I want all the wallpapers who have this tag -
How to do an category filter tab logic in django template with js or vue
I am working on categories and brands, one brand can have many categories and I am displaying a button for each category on a Django template and all the brands below but I want that when I press a button category only display the brands that have that category models.py class Filter(models.Model): text = models.CharField(max_length=20) def __str__(self): return self.text class Category(models.Model): filter = models.ForeignKey(Filter, on_delete=models.CASCADE, null=True) icon = models.FileField(upload_to='img', null=True) class Brand(models.Model): logo = models.ImageField(upload_to='img', null=True) url_logo = models.URLField(max_length=200, null=True) filters = models.ManyToManyField(Filter) views.py class HomePageView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'category_list': Category.objects.all(), 'brand_list': Brand.objects.all() }) return context index.html {% for category in category_list %} <a href="#"><i><img src="{{ category.icon.url }}" alt="{{ category.filter }}"></i>{{ category.filter }}</a> {% endfor %} {% for brand in brand_blocks %} <div> <a href="{{ brand.url_logo}}"> <img src="{{ brand.logo.url }}" /> </a> </div> {% endfor %} -
problems serving two django backend apps and two angular frontend app on the same ip address
i have a digitalocean ip address 143.20.20.14 ip set up with two domains members.com and sales.com to server two django app each with angular frontends. for each app i have setup separate files as follows: this is my members.com gunicorn socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target this is my sales.com gunicorn file gunicornsales.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicornsales.sock [Install] WantedBy=sockets.target this is my member.com gunicorn service gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/membersdir ExecStart=/home/webapps/membersdir/members_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ membersbackend.wsgi:application [Install] WantedBy=multi-user. this is my sales.com gunicorn.service file gunicornsales.service [Unit] Description=gunicorn daemon Requires=gunicornsales.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/salesdir ExecStart=/home/webapps/salesdir/sales_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicornsales.sock \ salesbackend.wsgi:application [Install] WantedBy=multi-user. my nginx files are as follows this is my members front end file membersfrontend server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html/membersfrontend; index index.html index.htm index.nginx-debian.html; server_name members.com; location / { add_header Access-Control-Allow-Origin *; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; try_files $uri $uri/ /index.html; } } this is my sales frontend file salesfrontend server { listen 80 … -
Can I use a single search bar for searching different things?
I'm trying to use a single search bar for searching different models. Is it possible to handle it with one view? my views.py file: class SearchResultsView(ListView): model = Food template_name = 'restaurant/food_search_results.html' context_object_name = 'data' def get_queryset(self): query = self.request.GET.get('search') if query is not None: return Food.objects.filter(name__icontains=query) else: return Food.objects.none() my models.py file: class Food(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_path) description = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) meal_category = models.ManyToManyField(MealCategory, related_name="meal") food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat") class Restaurant(models.Model): name = models.CharField(max_length=100) -
Prediction percent
I am searching to find solution. I can't make percent to my prediction. Here is only 0 for no risk and 1 - when pacient has heart disease. How can I upgrade my code and show percentage of risk? I've tried a lot of things, but it doesn't work. Still 0 and 1 predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True And here is my Logistic Regression example: from sklearn.linear_model import LogisticRegression classifier =LogisticRegression() classifier.fit(X_train,Y_train) y_Class_pred=classifier.predict(X_test) from sklearn.metrics import accuracy_score accuracy_score(Y_test,y_Class_pred) from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, y_Class_pred) from sklearn.metrics import classification_report print(classification_report(Y_test, y_Class_pred)) from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test)) fpr, tpr, thresholds = roc_curve(Y_test, classifier.predict_proba(X_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.savefig('Log_ROC') plt.show() Newdataset = pd.read_csv('newdata.csv') ynew=classifier.predict(Newdataset) -
Django code cannot install a pickled sklearn variable
I am building a Django site which contains a segmentation application. A difficulty I am having is importing the segmentation kmeans / hclusters variables which have been stored via joblib. To try to minimize the factors involved, I am building the clusters on the same machine (new M1 Macbook) as the machine I am loading the variables into. I have also utilized the same environment structure (both Python 3.10 environments) and synched the numpy, pandas and scikit-learn environments. I am unable to deduce what is preventing the joblib load in the Django environment. The error occurs when using pickle / pickle5 as well. Error message when attempting import: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 587, in load obj = _unpickle(fobj, filename, mmap_mode) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 506, in _unpickle obj = unpickler.load() File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1213, in load dispatch[key[0]](self) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1538, in load_stack_global self.append(self.find_class(module, name)) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1580, in find_class __import__(module, level=0) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/sklearn/cluster/__init__.py", line 6, in <module> from ._spectral import spectral_clustering, SpectralClustering File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module … -
get data from one column in db django
I have table in my db Users: id name last_name status 1 John Black active 2 Drake Bell disabled 3 Pep Guardiola active 4 Steven Salt active users_data = [] I would like to get all id and all status row from this db and write to empty dict. What kind of querry I should use? filter, get or smth else? And what if I would like to get one column, not two? -
Base "/" not found in Django
My django project ornaments has only one app called balls. I would like the server to point to its index when I do manage.py runserver. I changed urls.py as follows but I get this error: [![enter image description here][1]][1] from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('balls/', include('balls.urls')), path('admin/', admin.site.urls), ] urlpatterns += [ path('', RedirectView.as_view(url='balls/', permanent=True)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)``` I am also including the project structure. Please note that the string `ball` appears nowhere in my code (as per a search).[![enter image description here][2]][2] [1]: https://i.stack.imgur.com/6JL2c.png [2]: https://i.stack.imgur.com/1pjCg.png -
Get name of image when uploading
I am using this code to check the size of an image before uploading on the model. I would like to get the image name so I can communicate to the users what the offending file is. How would I go about this. def validate_image(image): file_size = image.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError("Max size of file is 3MB") image = models.ImageField(default='default.jpg',validators=[validate_image]) -
connect to rabbitMQ cloud using django and flas dockers
I am trying to follow a "Microservices Application with Django, Flask, Mysql" guide on youtube. In this example a Django app uses RabbitMQ (cloud version) to send the message that must be consumed. The following is the consumer.py import pika params = pika.URLParameters('amqps_key') connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='admin') def callback(ch, method, properties, body): print('Recevied in admin') print(body) channel.basic_consume(queue='admin', on_message_callback=callback, auto_ack=True) print('Started cosuming') channel.start_consuming() channel.close() I have an endpoint in the urls.py that calls the producer.py This is the docker-compose: version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db command: ["./wait-for-it.sh","db:3306","--","python","manage.py","runserver","0.0.0.0:8000"] db: image: mysql:5.7.36 restart: always environment: MYSQL_DATABASE: tutorial_ms_admin MYSQL_USER: ms_admin MYSQL_PASSWORD: ms_admin MYSQL_ROOT_PASSWORD: ms_admin volumes: - .dbdata:/var/lib/mysql ports: - 3308:3306 Now: if I start the docker-compose, then open a terminal, go inside the backend service and in the service shell type "python consumer.py", using Postman and enter the endpoint I can see the message being consumed (both in screen and in the rabbit cloud administration panel). If I tried to add the python consumer.py as a command after the "wait-for-it.sh.... " it does not work. Messages are stuck in the Rabbit cloud administration panel, as if nothing consumes them. … -
Ajuda em Django com Python Erro
Boa Tarde. Estou criando uma loja em Django (Estou aprendo ),tenho um erro que nao sei onde ele esta. Preciso de uma Luz.Ja verifique mas nao encontro o erro. O erro e este Agradeço desde ja pela Ajuda. (return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: lojaapp_pedido_order.carro_id). -
What kind of Authentification should I use for Django Rest? [closed]
I am trying to create a calendar mobile application which is being synchronised over multiple different devices using django Rest Api. I obviously have user specific data which is not supposed to be accessed by anybody else then the specific user. What is the best method of authentification for this kind of project? Also, could it be implemented, that the user does not have to sign in each time it opens the application again? -
JavaScript ajax call on page onload and retrieve data from views in Django
I wish to pass localStorage data to Django views and display the return record on page template on page load. I think it can be done with Ajax, but I have no Idea how I can pass specific localStorage variable to Django views on specific pageload and display the record on template as regular templating(not ajax html return) For example: If I load abcd.com/test URL, I want to pass an array of ids or something of a Variable, and return views on template according to passed values. Is there any better way of achieving this ? -
Trying to run task in a separate thread on Heroku, but no new thread seems to open
I have a Django app with a view in the admin that allows a staff user to upload a csv, which then gets passed to a script which builds and updates items in the database from the data. The view runs the script in a new thread and then returns an "Upload started" success message. apps/products/admin.py from threading import Thread # ... from apps.products.scripts import update_products_from_csv @admin.register(Product) class ProductAdmin(admin.ModelAdmin): # normal ModelAdmin stuff def upload_csv(self, request): if request.method == 'POST': csv_file = request.FILES['csv_file'] t = Thread(target=update_products_from_csv.run, args=[csv_file]) t.start() messages.success(request, 'Upload started') return HttpResponseRedirect(reverse('admin:products_product_changelist')) apps/products/scripts/update_products_from_csv.py import csv import threading from time import time # ... def run(upload_file): # print statements just here for debugging print('Update script running', threading.currentThread()) start_time = time() print(start_time) decoded_file = upload_file.read().decode('utf-8').splitlines() csv_data = [d for d in csv.DictReader(decoded_file)] print(len(csv_data)) for i, row in enumerate(csv_data): if i % 500 == 0: print(i, time() - start_time) # code that checks if item needs to be created or updated and logs accordingly print('Finished', time() - start_time) In development this works fine. The "Upload started" message appears almost immediately in the browser, and in the console it prints that it started on Thread-3 or Thread-5 or whatever, and then all the … -
Why keep getting SIGPIPE error after the page reloading several times ! using Django app with nginx for Bitcoin core gateway
I have Django app trying to make bitcoin payment page using local bitcoin core node but I keep getting ([Errno 32] Broken pipe) when the page refresh to check the incoming transactions the error looks like timeout error but I tried several methods to resolve timeout errors using uWsgi and Nginx params but didn't work and didn't got any benfet from logs only from journalctl got SIGPIPE: writing to a closed pipe/socket/fd The debug mode showing this Traceback (most recent call last): File "./wallet/models.py", line 235, in updatedeposit_btc unconf_amount = self.bitcoind.unconf_by_addr(address) File "./wallet/bitcoind.py", line 70, in unconf_by_addr return self.proxy.getreceivedbyaddress(addr, minconf=0) File "/project/env/lib/python3.9/site-packages/bitcoin/rpc.py", line 600, in getreceivedbyaddress r = self._call('getreceivedbyaddress', str(addr), minconf) File "/project/env/lib/python3.9/site-packages/bitcoin/rpc.py", line 231, in _call self.__conn.request('POST', self.__url.path, postdata, headers) File "/usr/lib/python3.9/http/client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1049, in _send_output self.send(chunk) File "/usr/lib/python3.9/http/client.py", line 971, in send self.sock.sendall(data) During handling of the above exception ([Errno 32] Broken pipe), another exception occurred: and I have in bitcoind connection setting .py from django.conf import settings from decimal import Decimal from .rates import rate import bitcoin import bitcoin.rpc from … -
list index out of range error from previous view when rendering a different view
Apologies if I'm missing something daft here but I'm new to Django and I can't work this out. I'm creating a basic reddit style app focusing on cryptocurrency. I have a view which gets price data from an API and displays it as well as any posts specific to that coin: views.py: def coin_posts(request, id): if request.method == 'GET': coin_display = {} post = Post.objects.filter(coin_name=id) api = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=%s&order=market_cap_desc&per_page=100&page=1&sparkline=false' % id response = requests.get(api) data = response.json() coin = data[0] coin_data = Coins( coin_id = coin['id'], coin_name = coin['name'], coin_price = coin['current_price'], market_cap = coin['market_cap'], rank = coin['market_cap_rank'], price_change = coin['price_change_24h'], slug = coin['symbol'], image_url = coin['image'] ) coin_data.save() coin_display = Coins.objects.filter(coin_id=id) return render(request, 'coins.html', { 'post': post, 'coin_display': coin_display, 'post_form': PostForm() }, ) I want to be able to click on each post to view any comments related to said post, as I haven't got that far yet I just wish to be able to view that single post on another page. So each post has the following link on the template: <a href="{% url 'coin_detail' slug=i.slug %}">Comments</a> and here are the corresponding URLs and view: urlpatterns = [ path('', views.index, name="index"), path('<str:id>/', views.coin_posts, name='coin_posts'), path('<slug:slug>/', views.post_detail, name='coin_detail'), ] def … -
Why is a check for an object passing through this if condition and then raising an AttributeError because it doesn't exist?
I've got models that look like this: class Agent(models.Model): pass # there's obviously more to this but for the sake of this question... class Deal(models.Model): agent = models.ForeignKey( Agent, on_delete=models.SET_NULL, null=True, blank=True ) Inside the save method of the Deal, I have some code that updates the metrics of the Agent that looks like this: class Deal(models.Model): agent = models.ForeignKey( Agent, on_delete=models.SET_NULL, null=True, blank=True ) # ... other code ... def save(self, *args, **kwargs): if (self.agent): try: self.agent.closing_success_rate = self.get_agent_closing_success_rate() except Exception as e: print(e) And when there is not an Agent connected to the deal, I get the error: "'NoneType' object has no attribute 'closing_success_rate'" How is the if condition that checks if the Agent exists passing only to later throw an error because it doesn't exist? -
Retrieving Hash (#) url-parameters in Django [duplicate]
I’m working with an Oauth integration and for the first time I’m experiencing that the callback from service uses a # instead of ? in the url params. What I’m used to: test.test/auth?token=123&timestamp=12345 This API: test.test/auth#token=123&timestamp=12345 (note the # between auth and token) So I figured the standard request.GET.get('token’) is not going to work here... well it doesn’t. Does Django have a way of dealing with # params or should write out my own function? Suppose this API is rather intended to be used by JS / Client Side apps, but would be nice to make use of that server side. Thanks! -
how can I separate the result of a query into groups - Django
I try to explain myself, I have the result of the events extracted from the db that have the sports league column. I would like to separate them in the loop so you have something like: League 1 => its events League 2 => its events League 3 => its events evenst list -
Can't pass a variable through my view to the html template
So I'm trying to: pass a variable owner_id in the view def new(request, owner_id) to render new.html that it will be used in the action of a form as a parameter/argument action="{{ url 'new' owner_id }}". Like This: def new(request, owner_id): # from here if request.method == 'POST': ... else: category = Category.objects.all() render(request, "auctions/new.html", { "category": category, "owner_id": owner_id # <--- to HERE }) view.py urls.py new.html Error detected in this file by django Layout.html template Could not parse the remainder ERROR screenshot It's driving me crazy... I can't understand why its not working. And the worst part is I already did it on another view and it WORKED! The only difference is here I use the same variable again inside in the form to "feed" it again, throught the same url, view... etc. Whether there (another url and view) I used it as a normal variable inside the brakets {{ }}. PD: I probably lack the basic understanding how django starts to process all this.