Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
ERROR: NotFoundError - Elastic Beanstalk can't find a platform version that matches "python-3.9"
I am trying to deploy Django project, but I am finding the below error ERROR: NotFoundError - Elastic Beanstalk can't find a platform version that matches "python-3.9" I am using python version 3.9, any suggestions will be highly appreciated -
problem with displaying ManyToMany Field in Dango templates
I have an app that for shopping list and I want to display values from my ingredients ManyToManyField but what I am getting instead is the name of the recipe that I created. Could you please advice me on how to correctly do it? models.py class Ingredients(models.Model): name=models.CharField(max_length=100, default='-', blank=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'składnik' verbose_name_plural = 'składniki' def __str__(self): return str(self.name) class Category(models.Model): name=models.CharField(max_length=250, default='-', blank=True, unique=True) slug = models.SlugField(unique=True, blank=True) class Meta: ordering = ('name',) verbose_name = 'kategoria' verbose_name_plural = 'kategorie' def get_absolute_url(self): return reverse("kategoria", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default='-') name = models.CharField(max_length=400, blank=False, unique=False) body = models.TextField(blank=True, default='') ingredients = models.ManyToManyField(Ingredients) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) date_created = models.DateTimeField('Utworzono', default=timezone.now) last_updated = models.DateTimeField('Ostatnia zmiana',auto_now=True) when_to_eat = models.DateField('Kalendarz', default=timezone.now) tags = TaggableManager() slug = models.SlugField(unique=True, blank=True) class Meta: ordering = ('name',) verbose_name = 'przepis' verbose_name_plural = 'przepisy' def get_absolute_url(self): return reverse("przepis", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) views.py class RecipeListView(ListView): model = Recipe template_name ='recipe_list.html' queryset = Recipe.objects.all() urls.py urlpatterns = [ path('przepisy/', views.RecipeListView.as_view(), name='recipe_list'), path('przepis/<slug:slug>/', views.RecipeDetailView.as_view(), name='przepis'), ] recipe_list.html <p class="card-text">Składniki:<br> {% for ingredient in object_list %} <li>{{ingredient.name}}</li> {% endfor %} </p> -
Python: Why wont CSS apply to Django?
I am working on a small Python + Django project, but for some reason the CSS wont apply. This is my folder structure: And this is how i implement the CSS, i have also added {% load static} at the top of my HTML file <link rel="stylesheet" href="{% static 'main/styles/base.css' %}"> The website doesn't crash or anything like that, the CSS simply is just not applied. Any ideas? -
Permissions In Django
Hello, Please am Trying to build a app which it has three user types 1. management 2. staff 3. accountant and the management user want to add and give certain permissions to a user of staff or accountant please help Models.py: class CustomUser(AbstractUser): user_type_data = ((1, "management"), (2, "staff"), (3, "finance")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) -
The file 'css/config/static/img/gallery/about-img2.png' could not bnde fou
Quien me puede ayudar con lo siguiente por favor. Esoty teniendo este error al subir mi proyecto Django a Heroku. por lo que entiendo y investigado la ruta esta mal, por lo cual me fui a la ruta donde estan llamando al respectivo archivo y la cambia como se registra en la imagen dos, pero el error sigue, como debo establecer las rutas donde estan esos archivos? en el css tambien tengo que utilizar url({% static 'ruta statica donde esta el archivo'%}) o como seria la estructuración? enter image description here enter image description here -
rendering django forms with one field inside other
I want to create following form with Django "forms". can anyone give me a clue how to create such form in which there is option to add text if radio button is selected and there would be two groups of radio buttons. There is no model for this form. If it is not possible with Django forms than how we can create it with Django framework. -
How to use reverse relation in my query?(django)
I'm trying to make a query to show all the branches which have the food. I've tried a lot but I can't make it work. Could someone help me? Here are my models: class Branch(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) is_main = models.BooleanField() description = models.TextField(max_length=500) food_restaurant_category = models.OneToOneField(FoodRestaurantCategory, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) branch_address = models.OneToOneField(BranchAddress, on_delete=models.CASCADE) manager = models.OneToOneField("accounts.Staff", on_delete=models.CASCADE) 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 Menu(models.Model): inventory = models.PositiveIntegerField() price = models.DecimalField(validators=[MinValueValidator(0.0)], max_digits=10, decimal_places=1) food = models.ForeignKey(Food, on_delete=models.CASCADE, related_name="food_rel") branch = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name="branch_rel") -
Django Customer with onetoone relationship with User - how to create the fields for that model when creating User?
Here is my problem - upon creation of User in django i want to also create Customer with Onetoone relationship. I was able to get this working but problem started when I wasn't able to also create fields - dob and mobile. (User is default django user) My forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] mobile = CharField(max_length=30) class CreateCustomerForm(ModelForm): class Meta: model = Customer fields = ['mobile', 'dob'] My models.py class Customer(Model): user = OneToOneField(User, on_delete=CASCADE) mobile = CharField(max_length=12,null=True) dob = DateField(null=True) def __str__(self): return self.user.username My views.py def customer_registration(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) Customer.objects.create( user=user, ) messages.success(request, 'Account was created for ' + username) return redirect('index') context = {'form': form} return render(request, 'signup.html', context) I need to add 2 more fields into that Customer model (dob=form.dob, mobile=form.mobile), I was trying to have second form for this but it wouldn't work. This is what I have tried: def customer_registration(request): form = CreateUserForm() form2 = CreateCustomerForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) … -
it is showing me ValueError at /edit/update/3 The view branch.views.updateuser didn't return an HttpResponse object. It returned None instead
in django python def updateuser (request , user_id ): updateuser = User.objects.get (user_id = user_id) form= userform (request .POST, instance = updateuser) if form. is_valid (): form .save() messages .success (request ,"Record Updated successfully.....!") return render(request,'bdata.html',{"User":updateuser}) -
how to alter model field to foreign key with existing tables
I have a simple model. This table has a few entries in the db. And, the category field of them is not empty: # blog.models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=50) I want to change the category field to foreign key. The category table is created as follows and those fields are changed to foreign keys: # blog.models.py from django.db import models from account.models import User class Category(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=100) # category = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, default=Category.objects.get(title=title)) I have these restrictions: the migration directory of the blog app shouldn't be deleted. the category key should point to a category object that has the same title equal to its own. If a category object gets deleted, the category field of articles pointing to it should become null. Here is my problem: When I perform migrate, django says raise self.model.DoesNotExist( blog.models.Category.DoesNotExist: Category matching query does not exist. This is because I have a few articles. But, the category table is empty. So, Django doesn't find any category object to point existing articles to. I tried to deleted category field's default value: category … -
how to add more attributes to what an api returns
I am trying to write an API using django rest framework in which, you give a username and a password and in return you get an AuthToken or in other words you login. now I want this API to also return some fields like the email of the user along with the AuthToken. so if the authentication was successful, the get an authToken and the user's email. Can anyone help me on how I could be able to do this by adding or changing a bit of my code? These are my models: class UserManager(BaseUserManager): def createUser(self, email, password=None, **extra_fields): if not email: raise ValueError('Email Not Found!!!') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def createSuperUser(self, email, password): user = self.createUser(email, password) user.isAdmin = True user.isSuperUser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) isSuspended = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) emailActivation = models.BooleanField(default=False) balance = models.IntegerField(default=0) objects = UserManager() USERNAME_FIELD = 'username' These are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('username','email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): return get_user_model().objects.createUser(**validated_data) def update(self, instance, validated_data): password = validated_data.pop('password', … -
How I can use pagination for my Class (DetailView) with get_context_data?
How can I get pagination for the current code? I can't change the DetailView to View or ListView, so in this class I get a filter of products. class CategoryDetailView(DetailView): model = Category queryset = Category.objects.all() context_object_name = 'category' template_name = 'category_products.html' ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... products = Product.objects.filter(id__in=[pf_['product_id'] for pf_ in pf]) context['category_products'] = products return context -
Python: How to setup virtuel enviroment?
I'm trying to set up a virtual environment for my Python + Django project, so I ran the following in my terminal: pip3 install pipenv Afterward while being in my folder I tried doing this pipenv install django but I keep getting this error, and I have no idea how to solve it. Not sure if this makes a difference but i work in VScode zsh: command not found: pipenv Any ideas on how to solve this problem? -
Can we deploy Django on Lambda without Zappa or Serverless (Want to use native CloudFormation or Terraform)
I'm new to Django, I'm a NodeJS developer, I used CloudFormation for deploying my NodeJS applications on lambda using codebuild and codepipeline, trying to replicate the deployment mechanism for Django on Lambda. Googling out, but all solutions are using Zappa or Serverless. Looking for something native way deploying Django applications on Lambda using CloudFormation or Terraform