Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access extra form field inside the model's overriden save function? DJANGO
I have a model as class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True) and form as class UserRegisterForm(UserCreationForm): email = forms.EmailField() city = forms.CharField(initial=get_location()) class Meta: model = User1 # model that is being affected is this model, .save will save to this and next is the fields to be displayed in the order fields = ['username', 'email', 'password1', 'password2', 'city'] Now when I override Profile's save method, I need to access the 'city' variable and create an object of Location model, which I will later attach to the instance of User, to be accessed in the signal function of creating a profile. I can also override the init of form to add the extra field, but not able to access the 'city' variable at all I can do this in a normal view function by request.POST, but how do I access the extra 'city' variable I created in form meta, inside the overriden model save or in overriden form init?? -
Invalid Block Tag - base.html. expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Django & Bootstrap Project
I've decided to switch my project Bootstrap from 3.3.7 to 4.0.0 and when I wrote my code this error popped up. What is the problem here? I'm a beginner, I know it isn't that hard. base.html <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'home' %}">Chat & Write</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% if user.is_authenticated %} <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'profile' %}">Profil</a> <a class="nav-item nav-link" href="{% url 'writers:all' %}">Scriitori</a> </div> </div> {% endif %} <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% posts:create %}">Postare</a> <a class="nav-item nav-link" href="{% groups:all %}">Grupuri</a> <a class="nav-item nav-link" href="{% groups:create %}">Creaaza grup</a> <a class="nav-item nav-link" href="{% polls:polls %}">Polluri</a> <a class="nav-item nav-link" href="{% accounts:logout %}">Log Out</a> {% else %} <a class="nav-item nav-link" href="{% groups:all %}">Vezi grupurile</a> <a class="nav-item nav-link" href="{% accounts:login %}">Login</a> <a class="nav-item nav-link" href="{% accounts:logout %}">Log Out</a> {% endif %} </div> </div> </div> </nav> </header> -
How to overload get method in the same view in DRF?
I am trying to overload the get request method in my view but it's not working. The view class HomeworkListView(APIView): def get(self, request, teacher): hws = Homework.objects.filter(teacher__user__username=teacher) if not hws.exists(): return Response({'message': 'No homework given by this teacher.'}, status=status.HTTP_204_NO_CONTENT) serializer = HomeworkSerializer(hws, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def get(self, request, school_id, class_name): hws = Homework.objects.filter(school_id__school_id__username=school_id, class_name__class_name=class_name) if not hws.exists(): return Response({'message': 'Homework for this class does not exist.'}, status=status.HTTP_204_NO_CONTENT) serializer = HomeworkSerializer(hws, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('list/<slug:teacher>', HomeworkListView.as_view()), path('list/<slug:school_id>/<slug:class_name>', HomeworkListView.as_view()), ] The second get method method is working but the first one throws a TypeError: get() got an unexpected keyword argument 'teacher'. I am guessing if I change the order of the URLs then the first one will work but not the second one. Am I missing something or this is just not possible at all? -
What is the purpose of 'pop' in python?
I ended up having to use this in my django app within a ModelForm. Of what I have researched it picks and removes an attribute, but why would we want to ever remove data like this? class SomeView(FormView): def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs class SomeForm(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super().__init__(*args, **kwargs) ... ... I figured out that in this case it makes the function work because the init function isn't expecting that value even though I need it. But this feels kinda hacky, throwing it in a view earlier on and then popping it out so it doesn't cause problems. Wouldn't we want to just find a more clean way to do this, or is this considered the best way? -
Django Rest framework cant join tables
I am trying to fetch related data from a parent table using an API. I am trying to get the details from the operator table which has a one-to-one field with the user table. After going through various answers I understood how to join tables but due to some reason I am unable to fetch the user data serializer.py class OpDetailsSerializer(DynamicFieldsModelSerializer): user = UserSerializer(source="operator_details",many=False, read_only=True) print(user.data) class Meta: model = OperatorDetails fields = ('gst_no','pan','user') models.py class OperatorDetails(models.Model): operator=models.OneToOneField(settings.AUTH_USER_MODEL,related_name="operator_details",on_delete=models.CASCADE,primary_key=True) pan = models.CharField(max_length=10, unique=True, null=True,blank=True) gst_no = models.CharField(max_length=15, unique=True,null=True,blank=True) def __str__(self): return str(self.operator) views.py def view_operator_info(request): fields = ('operator','pan','gst_no','user') operator = OperatorDetails.objects.get(operator__id=request.user.id) serializer = OpDetailsSerializer(operator,fields=fields) content = { "status": True, "response": status.HTTP_200_OK, "message": "Operator details", "data":serializer.data } return Response(content) Actual Output { "status": true, "response": 200, "message": "Operator details", "data": { "gst_no": "test", "pan": "test" } } expected Output { "status": true, "response": 200, "message": "Operator details", "data": { "gst_no": "test", "pan": "test", "user":{ "email":..... //data from user table } }} can anyone help. Thanks in advance -
get() returned more than one Product -- it returned 14
I am a student currently learning Django. When I register the product, I want to complete the product registration by specifying the product option, and I want to get the product_code of the option model from get. I wrote this code, but the get_object part keeps getting errors. There are currently 14 registered products, so I think there is an error like above, so please tell me how to solve it. I would appreciate it if you could let me know. I'd like to ask you very much. views.py from django.shortcuts import render, redirect, get_object_or_404 from zeronine.models import * from .forms import ProductForm, OptionForm # Create your views here. def product_upload(request): current_category = None categories = Category.objects.all() products = Product.objects.all() slug = Product.slug if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = Product() product.name = form.cleaned_data['name'] product.benefit = form.cleaned_data['benefit'] product.detail = form.cleaned_data['detail'] product.target_price = form.cleaned_data['target_price'] product.start_date = form.cleaned_data['start_date'] product.due_date = form.cleaned_data['due_date'] product.category_code = form.cleaned_data['category_code'] product.image = request.FILES['image'] product.username = request.user product.slug = slug product.save() if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option = Option() option.name = form.cleaned_data['option_name'] option.product_code = get_object_or_404(Product) option.save() return render(request, 'zeronine/list.html', {'form': form, 'current_category': current_category, 'products': products, 'categories': categories, 'slug': slug}) else: … -
Capturing the data entered by a user, and displaying it on the same page
As my course project, I am making a supermarket management system. I am using Django with MySQL. I have already connected these two, and I am able to send data to the database and retrieve the same from it just fine. I have a relation in MySQL for PRODUCTS (product_id, product_name, brand_name, price). After the cashier enters the name of the product and the quantity that the customer wishes to purchase, I want the information related to that product along with the quantity to be displayed on the same page. Since a customer can purchase many different products, I want the information to be displayed as and when the cashier enters the names of those products. Then, I want to retrieve the information of all those products that were added by the cashier, and store it in the database in a relation called ORDERED_ITEMS (order_id, product_id, quantity) [order id is a foreign key]. I have no clue as to how to go about doing these things. Any help would be greatly appreciated. transaction.html: <form action="/transaction" method="post"> {% csrf_token %} <label for="order_id">ORDER ID</label> <input type="number" id="order_id" name="order_id" value="{{ next_order_id }}" disabled> <h3>ADD PRODUCTS :</h3> <label for="product_id"> Product ID</label> <select name="product_id" id="product_id"> … -
Could not resolve URL for hyperlinked relationship using view name "conversation-detail"
I'm building an rest api in django rest but I'm getting this and I don't know how to solve it. "ImproperlyConfigured at /conversation/1/ Could not resolve URL for hyperlinked relationship using view name "conversation-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. " models.py class Conversation(models.Model): storeId = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True) operatorId = models.ForeignKey(Operator, on_delete=models.SET_NULL, null=True, related_name='operatorId') clientId = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) operatorGroup = models.ForeignKey(Operator, to_field='group', on_delete=models.SET_NULL, null=True, related_name='operatorGroup') views.py class ConversationApiView(APIView): def get(self, request, id, *args, **kwargs): conversations = Conversation.objects.filter(id=id) serializer = ConversationSerializer(conversations, context={'request': request}, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class ConversationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Conversation fields = ('__all__') ursl.py urlpatterns = [ path('conversation/<int:id>/', ConversationApiView.as_view()), path('chat/<int:id>/', ChatApiView.as_view()), ] root urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('api.urls')), ] THANK YOU in advance! -
How can i set default Username as what in email field in Django?
I want to set a default username when the user is created. I am using Django For example: in Freelancer.com when users signup, their username will be by default @their_email if I register with email -> john123@gmail.com My username will be -> @john123 How can I do it in the Models? My current Models is: from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class User(AbstractUser): """Default user for Mofidon.""" #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) class CustomAccountManager(BaseUserManager): def create_user(self, email, name, username, password, **other_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( email=email, name=name, username=username, **other_fields ) user.set_password(password) user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): name = models.CharField(_("Name of User"), max_length=100) # username = models.CharField(_("Username of User"),max_length=20,unique=True, blank=True, null=True) username = None email = … -
Output PDF from HTML with Django in 2021
What is the best package to create professional report and invoices using Django today? I`ve tried severals of them but I am encountering some issues. Best Regards, -
django-allauth login_redirect page with username as slug
I am using Django 3.2 and django-allauth 0.44 I have set my LOGIN_REDIRECT_URL in settings.py as follows: LOGIN_REDIRECT_URL = 'profile-page' in urls.py, I have the following route defined: path('accounts/profile/slug:username', AccountProfileView.as_view(), name='profile-page'), When I log in, (unsurprisingly), I get the following error message: NoReverseMatch at /accounts/login/ Reverse for 'profile-page' with no arguments not found. 1 pattern(s) tried: ['accounts/profile/(?P[-a-zA-Z0-9_]+)$'] How do I pass (or specify) a parameter of the logged in user's username to the route? -
send emails for newsletter when a row is added in database table through Django Admin
I need to know How to send Emails for Newsletter automatically when a row is Added to a table Through Django Admin Portal -
coverage API in a gunicorn wsgi django server
I am using the coverage 5.5 API to run code coverage on my server. This server is written using Django. I have implemented the solution as per this answer -- https://stackoverflow.com/a/20689873/2996407 When I start up my server on my localhost using manage.py runserver and then shut it after some time, the code coverage report is generated as expected and correctly indicates the code coverage as well. However, on my firm's staging env, the server is run as a docker container wherein 8 gunicorn workers are spawned. 8 individual coverage files are being generated as per the solution above which is expected as well. However, the report doesn't have any coverage. The only coverage that is being done is of empty __init__.py files. The above SO answer suggests using a single gunicorn worker, but I don't have the option to do that. However, it suggests creating coverage files per worker which is happening as expected. But no luck in getting the coverage report from those. -
Django & Tagulous - Displaying Posts from two filters within my queryset
I am wanting to display Posts based on two filters (Date Posted - Which I have already got working) but I wanted to also display posts based on which Tagulous tags are stored as apart of the currently logged in user's meta data. For example, if User A has the tag "Summer" stored as apart of their metadata, the logged in user would only see posts relating to the "Summer" tag and wouldn't see any Posts which have been created under any other tags such as "Autumn, Winter, or Spring." I've made a basic start with implementing in the Tagulous filters, but not too sure which direction to go in from here. class PostListView(LoginRequiredMixin, ListView): model = Post template_name = 'core/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = PAGINATION_COUNT def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) all_users = [] data_counter = Post.objects.values('author')\ .annotate(author_count=Count('author'))\ .order_by('-author_count')[:6] # Tagulous objects getseason = Season.objects.filter(season='winter') user_tag = Season.tag_model.objects.filter(season__owner=request.user) for aux in data_counter: all_users.append(User.objects.filter(pk=aux['author']).first()) data['preference'] = Preference.objects.all() data['all_users'] = all_users print(all_users, file=sys.stderr) return data def get_queryset(self): user = self.request.user qs = Follow.objects.filter(user=user) follows = [user] for obj in qs: follows.append(obj.follow_user) return Post.objects.filter(author__in=follows).order_by('-date_posted') Any assistance or guidance would be most appreciated! :-) -
Django File not uploading inlineformset createview
My UpdateView working but I am not understating why file is not uploading in my CreateView? here is my code: froms.py class BlogForm(ModelForm): class Meta: model = Blog fields = ['title','body'] ImageFormSet = inlineformset_factory(Blog,BlogHeaderImage,fields=('image',),extra=1) views.py class BlogCreate(CreateView): #file is not uploading in create view? model = Blog template_name = 'blog_post.html' form_class = BlogForm def get_context_data(self, **kwargs): kwargs['latest_posts_list'] = Blog.objects.order_by('-id') return super(BlogCreate, self).get_context_data(**kwargs) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ImageFormSet(self.request.POST, self.request.FILES) else: data["children"] =ImageFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() return super().form_valid(form) def get_success_url(self): return reverse("blog") class BlogUpdate(UpdateView): # Updateview is working and image file is uploading model = Blog template_name = 'blog_update_post.html' #fields = ['author','title','body'] form_class = BlogForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ImageFormSet(self.request.POST, self.request.FILES, instance=self.object) else: data["children"] =ImageFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() return super().form_valid(form) def get_success_url(self): return reverse("blog") I am also not getting any errors. After click on update button I successfully redirected in Blog page without uploading file. -
Django Doc Error in Forms in views: AttributeError: module 'mdntuto.views' has no attribute 'hello'
I had read entire forms on Django documents for 3.2.2 and now I am working on the practical provided in documentation for forms and faced AttributeError: The code copied as it is from Django Docs. Still leaves an error. I have checked 4 times didn't find error Error is: path('hello/', views.hello, name='hello'), AttributeError: module 'mdntuto.views' has no attribute 'hello' Code is as follows forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) user_name = forms.CharField(label='Last name', max_length=20, required=True) mobile_number = forms.IntegerField(label='Contact No.') email = forms.EmailField(label='Email Address', initial='foo@foo.com', required=True) date_of_birth = forms.DateField(label='Enter DOB', initial='YYYY-MM-DD format') views.py from django.http import HttpResponseRedirect from .forms import NameForm from django.http import HttpResponse from django.shortcuts import render def get_hello(request): # if use def hello(request): it works fine # def get_hello(request) is as per Django Docs. if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render (request, 'mdntuto/hello.html', {'form': form}) hello.html <form action="/your-name/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> -
Django sum of time differences from model fields
I'm trying to get the sum of time differences from model fields in Django. I've tried this but I get an empty result with no error: model.py class Project(models.Model): design_start = models.DateField(editable= True, default=datetime.today, blank=True) design_end = models.DateField(editable= True, default=datetime.today, blank=True) class Portfolio(models.Model): projects = models.ManyToManyField(Project) I'm trying to get the total design time of all the projects by subtracting design_start from design_end and then getting the sum of everything views.py class DashView(generic.ListView): context_object_name = 'project_list' template_name = 'index.html' queryset = Project.objects.all() def get_context_data(self, **kwargs): context = super(DashView, self).get_context_data(**kwargs) context['design_time'] = Portfolio.objects.all().annotate( design_time = ExpressionWrapper(Sum(F('projects__design_end') - F('projects__design_start')), output_field=DurationField()), ) return context urls.py urlpatterns = [ path('', views.DashView.as_view(), name='home'), ] index.html <h4>{{ design_time.design_time }}</h4> -
Specify two arguments in URL parameters for path Djano
I've currently got an endpoint that accepts GET requests, to retrieve users within a date range (there's no real need to explain the 'why'). The specific endpoint looks like this: GET /users/?fromdate={yyyy-mm-dd}&todate={yyyy-mm-dd} For example, I can have a request such as: GET /users/?fromdate=2017-01-01&todate=2017-04-01 Without going too much into detail on the urls.py and views.py, I've specified the router register and path to accept requests to this endpoint (which works fine): urls.py: router = routers.DefaultRouter() router.register(r"user", views.UserViewSet, basename='user') urlpatterns = [ path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user') ] I am now trying to run a unit test just to send a request to this endpoint Part of my test_user.py class looks like this: def test_user_list(self): response = self.client.get(reverse('user', kwargs={'fromdate': '2017-01-01', 'todate': '2017-04-01'})), format='json') self.assertEqual(response.status_code, 200) However, when I run the unit test, I get an error: Reverse for 'user' with keyword arguments '{'fromdate': '2017-01-01', 'todate': '2017-04-01'}' not found. 1 pattern(s) tried: ['/user/$'] I think the error is due to the fact that my path (while it works manually through a REST client like Postman) doesn't specify the arguments to expect path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user') So how do I specify the arguments to satisfy a 'fromdate' and 'todate' as above? I have had a … -
How do I resolve fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping in Graphene?
I'm trying to create a person schema in django with graphene using attrs structure and destructure so that my data is inputted into the DB using JSONB. So far this is what I've created: models.py: from django.db import models # Create your models here. class PersonModel(models.Model): data = models.JSONField(null=True) schema.py: # from typing_extensions import Required import graphene import cattr from graphene_django.types import DjangoObjectType from graphene import Mutation, InputObjectType,ObjectType, String, Boolean, Field, Int, List, NonNull, ID, Argument from .models import PersonModel from .person import PersonDataClass class PersonSchema(DjangoObjectType): id = Int, name = String, age = Int, address_one = String, address_two = String class Meta: model = PersonModel class PersonSchemaOutput(PersonSchema, DjangoObjectType): # notice we only need ID in output and not in input of Mutation of Create id = graphene.ID class Meta: model = PersonModel pass class PersonSchemaInputCreate(PersonSchema, InputObjectType): id = graphene.ID class Meta: model = PersonModel pass class PersonSchemaInputUpdate(InputObjectType): # lets say we only allow update of following class Arguments: id = graphene.ID name = String, age = Int, class Meta: model = PersonModel pass class CreatePerson(graphene.Mutation): ok = Boolean() class Arguments: first_name = graphene.String() age = graphene.Int() address_one = graphene.String() address_two = graphene.String() person_data = Argument(PersonSchemaInputCreate()) # output will be … -
save() takes 1 positional argument but 2 were given djnago allauth resetpassword form
I need to add recaptcha field to allauth reset password form , i override the form according to allauth documantion this is resetpassword form in forms.py : class MyCustomResetPasswordForm(ResetPasswordForm): captcha = ReCaptchaField() def save(self): # Ensure you call the parent class's save. # .save() returns a string containing the email address supplied email_address = super(MyCustomResetPasswordForm, self).save(self) # Add your own processing here. # Ensure you return the original result return email_address and in settings.py : ACCOUNT_FORMS = {'reset_password':'user.forms.MyCustomResetPasswordForm'} but i get this error : TypeError at /accounts/password/reset/ save() takes 1 positional argument but 2 were given Traceback Switch to copy-and-paste view /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 70, in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 98, in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 102, in post response = self.form_valid(form) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 690, in form_valid form.save(self.request) … -
ERROR when called from view: You can't execute queries until the end of the 'atomic' block
I'm trying to test a view that imports csv file and creates Product objects. The problem is that it returns this error: line 447, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The error is caused by this row: Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[ This is the method: @classmethod def import_csv(cls, filepath: str, created_by: User, delete_file=True) -> int: """imports products SKU already exists ? skip product : add product """ from products.models import Product from products.models import Supplier products_count = 0 EXCLUDED_ATTRS = ['id', 'supplier'] with open(filepath) as f: reader = csv.DictReader(f) for row in reader: if not all([row.get(field, None) is not None for field in ['sku', 'supplier__name']]): continue product = Product() product.created_by = created_by for attr, val in row.items(): if hasattr(product, attr) and attr not in EXCLUDED_ATTRS: if attr == 'title': setattr(product, attr, val[:99]) else: setattr(product, attr, val) supplier__name = row['supplier__name'] if supplier__name: supplier = \ Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[ 0] product.supplier = supplier try: product.save() except IntegrityError: pass # todo what? else: products_count += 1 if delete_file: os.remove(filepath) return products_count And this is a view action: @action(methods=['post'], detail=False) def import_csv(self, request, pk=None) -> Response: csv_file = … -
Using google geocoding with django
I'm trying to create a web application in django where a user can enter his postal code and then have nearby restaurants displayed. However, i can't figure out a way to get django to collect the json response from the google api call and use on my site. Ive tried looking around online for help but i can't seem to make any of them work. Can anyone see how to improve my views.py or if i need to add something into my urls.py or if there's another method. (I do not intend to store the postal code in my db btw) EXAMPLE OF GEOCODING JSON RESPONSE { "results" : [ { "address_components" : [ { "long_name" : "1600", "short_name" : "1600", "types" : [ "street_number" ] }, { "long_name" : "Amphitheatre Parkway", "short_name" : "Amphitheatre Pkwy", "types" : [ "route" ] }, { "long_name" : "Mountain View", "short_name" : "Mountain View", "types" : [ "locality", "political" ] }, { "long_name" : "Santa Clara County", "short_name" : "Santa Clara County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "California", "short_name" : "CA", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : … -
I am using Python 3.9.4 and Django 3.2 and I made a function and a form that to check if the username or email already exists
I am getting an error tuple indices must be integers or slices, not User also tuple indices must be integers or slices, not NoneType I am checking whether any of these username or email exists or not, also the exists() not working only first() not working note I am using python 3.9.4 if User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists(): error_message = '' email_error = ('', 'Email is taken. ')[User.objects.filter(email=email).exists()] username_error = ('', 'Username is taken. ')[User.objects.filter(username=username).exists()] error_message = email_error + username_error messages.success(request, error_message) return redirect('/register/') -
Django function for views takes too long
I'm currently using a Docker & Django setup. I have to fill a database with data from API requests. I was hoping to do this everytime you went on a certain page (pretty easy: just have your views.py call the function that fills the database and voila). But the problem is, the function takes a long time, several minutes from within django (and about half the time with Spyder). So I usually just get a TimeOut and the page never loads (I admit I have a lot of API requests being made). I've read some stuff on using Celery but am not quite sure how it's supposed to work. Anyone know how I could get around this to be able to load the database? -
Can anybody change below code to djagno orm?
Can anybody change below code to djagno orm? SELECT max(comic_chapter),comic_english_name_id FROM mangazones.mangabank_comic_banks group by comic_english_name_id;