Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
call view function in celery beat task (Django)
i want call del_cart() function in views.py, with celery beat tasks, but i cant found any way to call del_cart in del_cart_task views.py def del_cart(request): cart_obj = Cart(request) cart_obj.remove_all() return HttpResponse('your cart expire') tasks.py @app.task(name='remove_cart_session') def del_cart_task(): pass url.py urlpatterns = [ path('add_cart/', views.AddCart.as_view(), name='add_cart'), path('show/', views.ShowCart.as_view(), name='show'), path('remove/', views.del_cart, name='remove'), ] -
can not access webpage django
i am working on user's page on django. i want to enter http://127.0.0.1:8000/user/2 and get my template but django says The current path, user/2, didn’t match any of these. my view: from django.shortcuts import render from django.views import generic from .models import * def UserPage(request,user_num): #get user info username = "none" posts = []#post("test", "none") status = 'aboba' return render( request, 'userpage.html', context={'username': username, 'posts': posts, 'status': status}, ) my urls: from django.urls import path from . import views urlpatterns = [ path(r'^user/(?P<user_num>\d+)$', views.UserPage, name='userpage'), ] -
how customize django graphql-jwt
how customize backend authenticate for graphql-jwt? If i user BaseBackend and return user i get exception " graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'is_anonymous' " class MyBackend(BaseBackend): def authenticate(self, request, *profile): user = User() user.social_id = int(profile.get('user_id')) user.expires_at = profile.get('expires_at') user.last_verification_code = "{:04}".format(random.randrange(1, 10**4)) user.set_unusable_password() user.save() token = get_token(user) authenticate(username=user.full_name, password=user.password) login(request, user, backend='graphql_jwt.backends.JSONWebTokenBackend') return user -
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (set_session cannot be used inside a transaction)
raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (set_session cannot be used inside a transaction) -
Django Files Upload from Form get CSRF Forbidden on production
I have a simple Django FileForm for multiple files upload (basically txts with polygon coordinates). I don't want to save the uploaded files anywhere but only treat them on the fly (memory?) and return a leaflet map with the polygons and a new file of mine (which transforms and exports all the txts in a .dxf format file (CAD combatible)). I have done all the logic and my programm seems to work fine on development but on production (Heroku) when i hit the submit button on my form I keep getting CSRF Forbidden 403 message. I am really frustrated. I have used csfr decorators (csrf_exempt, requires_csrf_token, ensure_csrf_cookie) on my views but none seems to work. I have included enctype="multipart/form-data"> and {% csrf_token %} on my form template. What's the problem? It's hard for me to test and try because on development everything is ok and I have to deploy everytime only to see if another approach works. Is it because I am not saving the files on a model and on a disk (What's the logic here?), or is it because I'm missing something on the CSRF part on my settings? settings.py (when deploying) """ Django settings for myKAEK project. … -
Diffrence between user and user_id in get() functions [Django]
UserProfile.objects.get(user=request.user) UserProfile.objects.get(user_id=request.user.id) these two line of codes are returning the same object. so what is the diffrence between them ? -
I want to CRUD the comments of a django user
What you want to achieve When a user posts a comment for a movie, I can only comment on that comment and I want to update and delete it without changing the URL. What you want to ask How do I get my post to appear at the top of new posts when users post comments? How should I change delete and update when I change the url of the posted comment? Current code def view_movie_detail (request, movie_id): if not (Movie.objects.filter (id = movie_id)): Movie (id = movie_id) .save () movie = Movie.objects.get (id = movie_id). if request.method == "POST" and not (Comment_movie.objects.filter (user = request.user, movie = movie_id)): form = Comment_movie_CreateForm (request.POST) if form.is_valid (): Comment_movie ( comment = form.cleaned_data ['comment'], user = request.user, stars = form.cleaned_data ['stars'], user = request.user, star = form.cleaned_data ['stars'], Movie = movie ). Save () return redirect ('view_movie_detail', movie_id = movie_id) Otherwise form = Comment_movie_CreateForm () data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=ja-US") Recommendation = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed (Comment_movie.objects.filter (movie_id = movie_id)) Mean = movie.average_stars () Context = { "data": data.json (), "Recommendations": recommendations.json (). "Type": "Movie", "Comment": Comment "average": average value, "form": form. } return render (request, "Movie / movie_detail.html", context) … -
This error is displayed when running Django-> TemplateDoesNotExist
Error: TemplateDoesNotExist at /finance/charge/ view: class ChargeWalletView(View): form_class = ChargeWalletForm template_name = 'charge_wallet.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class}) urls: urlpatterns = [ path("charge/", ChargeWalletView.as_view(), name="") ] -
Use dj-rest-auth login token to access @login_required view
I would like to do a Django all auth login process via the drf. I use dj-rest-auth for this. After I get the authToken, I use it in the header to authorize the individual requests. However, as soon as I try to call a view that contains the @login_required decorator I am still redirected to the login page. I get the authtoken as follows: payload = {'username': '***', 'email': '***', 'password': '***'} r = requests.post("http://127.0.0.1:8000/dj-rest-auth/login/", data=payload, timeout=5) print(r.content) If I execute this request with this token, for example, everything works as intended: headers = {'Authorization': 'Token ***', 'content-type': 'application/json', 'Accept': 'application/json'} r = requests.post("http://127.0.0.1:8000/dj-rest-auth/user/", headers=headers, timeout=5) print(r.content) ...I get the related user details. However, when trying to access a view that has the decorator @login_required using the same auth header, I get redirected to the signin page. Why am I not being logged in? @login_required def home(request): return HttpResponse('It works!') -
how can I pass value from django forms to Excel?
I have a model with static values that I want to use in my model methods and 1 column with values that the user needs to insert called number_of_units. What I want to do is export the CostCalculator but the value in the number_of_units column should be taken from Django form, not from the model. How can export the value from number_of_units to the excel column? The form is saved successfully and I can see value from the form in the admin panel but in Excel, I see the value 0 in all rows. It seems that it takes only fixed values that are in the model but doesn't the value from the form. How can I fix that and pass the value from the form to Excel? forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(min_value=0) class Meta: model = CostCalculator fields = ('number_of_units',) resources.py class CostCalculatorResource(resources.ModelResource): related_product__title = Field(attribute='related_product__title', column_name='Product') number_of_units = Field(attribute='number_of_units') class Meta: model = CostCalculator models.py class CostCalculator(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product') title_component = models.ForeignKey(CalculatorServiceComponent, on_delete=models.CASCADE, default=1) number_of_units = models.IntegerField(default=0) views.py class ModelDetailView(FormMixin, DetailView): model = Product form_class = CalculatorForm template_name = 'ModelDetailView.html' def form_valid(self, form): number_of_units = form.cleaned_data['number_of_units'] filter_qs = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) dataset = CostCalculatorResource().export(filter_qs, … -
Is mandatory to refer foreign key even it has only one parent?
lets assume that there is an institution and this institution has many announcement so I intend to store these announcements in a table. Here is how it looks, class institution: - name - address, - .....etc class announcements: - owner = models.ForeignKey(Institution, on_delete=models.CASCADE) - messages, - ...etc From this, there wont be any new Institution, so do i really need to add FK in announcements table ?or can i simply create a table without FK as i can directly call the announcements without need to FK -
how can i solve this strenge error in python making django
this is my code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), ] and this is the error: in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings -
Django todoApp coming problem in adding task
I am getting problems with added tasks. It shows MultiValueDictKeyError in my code. Here is my source code -- https://github.com/Aliwahid17/todoApp Please help me in solving the problem. -
add 0.17 value to database in condition Django
I'm working on django-form project with some customer detail, all things are good condition work properly but a value of tax 0.17 is not added in tax column, tax column still show NULL value in database and all other value added successfully, I use checkbox in tax field in my html form I want if taxamount == ['0.17'] a value 0.17 is added in tax column else 0 added in tax column with other value (print function is just use to check that my condition is working or not but condition work properly) models.py class CustomerDetail(models.Model): customer_name = models.CharField(max_length=200) customer_number = models.CharField(max_length=200) Ship_No = models.IntegerField(primary_key=True) Cell_qty = models.FloatField(null=True, blank=True) Cell_price = models.FloatField(null=True, blank=True) thimble = models.FloatField(null=True, blank=True) thimble_price = models.FloatField(null=True, blank=True) tax = models.FloatField(null=True, blank=True) DatePur = models.DateTimeField(auto_now_add=True) Description = models.CharField(max_length=200, null=True, blank=True) view.py def addcustomer_view(request): if form.is_valid(): taxamount = request.POST.getlist('taxamount') if taxamount == ['0.17']: print('Tax added to database') CustomerDetail.tax = 0.17 else: print('Tax not added to database') CustomerDetail.tax = 0 form.save() return render(request, "customer.html") or is there any other way if checkbox is checked add 0.17 value to database otherwise add 0 to database in tax column -
remove Decimal like we remove 'u' for unicode how can we remove Decimal for the above problem
({'user__username': u'allen.davoudpour@compass.com', 'total': Decimal('599.97'), 'user__company__name': u'Allen Davoudpour', 'reference': u'1143001681', 'product__group__name': u'Property Video'}, {'user__username': u'Ross.McGinley', 'total': Decimal('150.00'), 'user__company__name': u'Slater Hogg Cumbernauld ', 'reference': u'4011416', 'product__group__name': u'Property Video'}) -
Bespoke form on Django - dropdown menu matching models choices
I am creating a form with all sorts of headers and question before each field. I initially create a form in Forms.py, but it seems quite difficult to customise it the way I want it. I resorted to build the form in the html template. I am struggling to create a drop down menu. In this example, when selecting the colour, users would have 4 choices listed in the choices in models.py. I am clearly not linking the form in the template to the actual form. What am I doing wrong? Here is the code Models.py LOOKCOLOUR=( (1,'Straw'), (2,'Yellow'), (3,'Gold'), (4,'Amber'), ) class ChampageRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="champcomments", on_delete=models.CASCADE) look_colour=models.IntegerField(choices=LOOKCOLOUR, default=0) .. def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) forms.py class ElderFlowerChampForm(ModelForm): class Meta: model = ChampageRating fields = ('look_colour', ) labels ={ 'look_colour': 'Colour', } widgets = { 'look_colour':forms.Select(attrs={'class':'form-control'}), } views.py def elderflowerchamp(request, product_id): global ChampageRating product = Product.objects.get(pk=product_id) url = request.META.get('HTTP_REFERER') submitted = False try: if request.method == "POST": reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST, instance=reviews) if form.is_valid(): form.save() return redirect('home') else: form = ElderFlowerChampForm(request.POST, instance=reviews) if form.is_valid(): ChampageRating = form.save(commit=False) ChampageRating.user = request.user ChampageRating.save() return redirect('home') else: #This part goes to … -
Heroku CLI error, can't access my django admin
I have deployed my backend of webproject through Heroku CLI. To access my database, I went through herokuapp.com/admin, but I got Internal Servor Error. So, I went to cmd to run heroku run bash command so that I can run migrations, but its showing this error. enter image description here My frontend which is in Next.js is deployed on Vercel and it shows my website. Just that I want to access my database to add data, and Heroku is giving me Problems. My database is Postgres. -
Change verbose name and help text on Django Admin Page
i'm developing a django site deployed via Nginx and PostgreSQL. I did some changes to my models.py and admin.py pages to correct a field. Yet this change is not being shown in my Django admin page, it's still with the old field names regardless of the change in my models.py folder. Here's the models.py and admin.py sections of code models.py title = models.CharField(max_length=100, help_text="Titulo del Proyecto", verbose_name="Titulo") subtitle = models.CharField(max_length=100, help_text="Subtitulo", verbose_name="Subtitulo") image = models.ImageField(upload_to='media/images',blank=True, help_text="Imagen del Proyecto", verbose_name="Imagen") slug = models.SlugField(max_length=100, help_text="No tocar", verbose_name="Slug") description = models.TextField(help_text="Descripcion del Proyecto", verbose_name="Descripcion") date = models.DateField() video_url = models.CharField(max_length=200, blank=True,help_text='Url del video ', verbose_name='Video URL') source = models.ForeignKey('Source', on_delete=models.CASCADE,blank=True, help_text='Youtube o Vimeo o NONE si no hay video',verbose_name='Source') category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, help_text='Categoria del projecto', verbose_name='Categoria') admin.py class ProjectAdmin(admin.ModelAdmin): pass list_display = ('title', 'date', 'category', 'source') list_filter = ('date', 'category', 'source') search_fields = ('title', 'description') ordering = ['-date', 'title'] date_hierarchy = 'date' fieldsets = ( (None, { 'fields': ('title','subtitle', 'description', 'image', 'date', 'video_url', 'source', 'category', 'slug') }), ) prepopulated_fields = {'slug': ('title',)} -
include tag vs block tag. The differences
What is the difference between the include tag and the block tag? In my opinion, it is much easier to use the include tag instead of the block tag. -
Increment Last Id from String in python Django
I am trying to generate auto increment number as a ID with Company Label. Company Label will be changes for every user. So I cant use slicing here. My ID is like TES-PRODUCT-01 TES is company label PRODUCT is as it is name But now I wish to change my last number when I am adding new product to TES-PRODUCT-02 and so on Getting Error can only concatenate str (not "int") to str Here is my code views.py def add_new_stock(request): stock_data=New_Stock_Entry.objects.all() if not stock_data: latest_item_code="TES-PRODUCT-001" else: latest_item_code = (New_Stock_Entry.objects.last()).item_code+1 get_tax_code=Tax_Settings.objects.values('name', 'tax_percentage','tax_id') if request.method == 'POST': item = request.POST['item'] hsn = request.POST['hsn'] item_code=latest_item_code stock_in_date=request.POST['stock_in_date'] quantity_in_hand=request.POST['quantity_in_hand'] sales_price=request.POST['sales_price'] item_description=request.POST['item_description'] unit=request.POST['unit'] tax_code = request.POST['tax_code'] tax_obj = Tax_Settings.objects.get(tax_id=tax_code) item_creation_details = New_Stock_Entry.objects.create(item=item, hsn=hsn, item_code=item_code,stock_in_date=stock_in_date,quantity_in_hand=quantity_in_hand,sales_price=sales_price ,item_description=item_description, unit=unit, tax_code=tax_obj) item_creation_details.save() print("item_details",item_creation_details) return render(request,"inventory/add-stock.html") return render(request,"inventory/add-stock.html",{'get_tax':get_tax_code,'latest_item_code':latest_item_code}) html <input type="text" class="form-control" placeholder="TES-PRODUCT-{{latest_item_code}}" name="item_code"> How Can I increment my last number from string? -
Why is Arrays.find() returning undefined in this situation?
I am following a Python/Django tutorial and the frontend part is done using React. I've reached a point where we're building reducers and actions and using Redux but while building the shopping cart I've reached a dead-end. Here is my reducer: import { CART_ADD_ITEM } from "../constants/cartConstants"; export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.type) { case CART_ADD_ITEM: const item = action.payload; const existItem = state.cartItems.find((x) => {return x.product === item.product}); if (existItem) { return { ...state, cartItems: state.cartItems.map((x) => x.product === existItem.product ? item : x ), }; } else { return { ...state, cartItems: [...state.cartItems, item], }; } default: return state; } }; The 'existItem' variable comes off as undefined, and I am expecting a boolean value. First, 'existItem' used to look like this const existItem = state.cartItems.find((x) => x.product === item.product); I read here about how to fix this issue but that didn't seem to make a difference. Whenever existItem is undefined I basically cannot keep adding items to my shopping cart and I cannot dynamically change their quantities. Where am I going wrong with this? -
Why doesn't my CSS style sheet link to my HTML template?
One of my HTML templates that extends the layout.html template has a CSS file linked to it but when I try to style the HTML content through the CSS file, nothing happens even after reloading. There is already a CSS file linked to the layout.html file but that does not style the page either. How do I make the style.css file style the new.html file (the page that should be styled)? Or should I make a new CSS file to style the new.html file? layout.html: {% load static %} <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> {% block style %}{% endblock %} </head> <body> {% block body %} {% endblock %} </body> new.html: {% extends "encyclopedia/layout.html" %} {% load static %} {% block title %} New Entry {% endblock %} {% block style %} <link href="{% static 'encyclopedia/new.css' %}" rel="stylesheet"> {% endblock %} {% block body %} <form action=""> <input type="text" name="title" class="title" placeholder="Title"> <textarea name="content" class="content" cols="30" rows="10" placeholder="Enter Content"></textarea> <input type="submit" value="Save" class="save"> </form> {% endblock %} style.css: /* styling for the layout page */ body { margin: 0; background-color: white; } code { white-space: pre; } … -
Trying to access a file in a subfolder in link django html
Lets say i have a file style.css which is located at TemplateData folder . Im currently recreating the path but problem is the parent folder of TemplateData is dynamically changing. So lets say i have : user/42/TemplateData/style.css or it could be user/66/TemplateData/style.css . How do i make the path so it can pass the number ? Im currently using : <link rel="stylesheet" href="{{ request.scheme }}://{{ request.get_host }}/{{ application.gameDirectory }}TemplateData/style.css"> and i am missing one folder between {{gameDirectory}} and TemplateData. -
Rendering Values in Html using Python Django
** HTML FILE ** {% extends 'shop/layouts/main.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <h1>Collections</h1> {% for item in items %} {{ item.name }} {% endfor %} </div> </div> </div> {% endblock content %} ** VIEWS.PY FILE ** from django.shortcuts import render from . models import * def collections(request): items = Product.objects.all() return render(request, "shop/collections.html", {"Item": items}) I need an help that I couldn't load my {items} on html it simply shows nothing in the output -
CORS Error when calling API from Lambda Custom Domain
I have a django backend that allow 2 domains(I am using django-cors) https://xxxxxx.execute-api.us-east-2.amazonaws.com https://mycustomdomainname.com When accessing the website through https://xxxxxx.execute-api.us-east-2.amazonaws.com the API calls work as expected. But when I access on my custom domain, I get CORS error Access to XMLHttpRequest at 'https://cool.api/api/v1/' from origin 'https://mycustomdomainname.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.