Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter using parent model's field
class Genre(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name I want to filter books with a specific genre as following: def get_books(genre="horror"): books = pd.DataFrame(list(Book.objects.filter(genre__name=genre).values())) print(books) But I get an empty dataframe printed. Is this filter syntax above correct? (That is a double underscores in the filter code) -
Why does my Django login work on development server but not production server?
I have an issue where I can login to Django via my development server but it will not work on the production server. I am using Heroku to deploy. All the pages work correctly but I can't login to my Django database. -
How to add model instances to a Foreign Key field in Django Rest Framework
I need to get the ItemModel instances from the item model and store them in the foreign key field in the OrderModel but I am not sure how. I've tried to iterate through the item order list and add one but it doesn't display correctly. Any help would be much appreciated. My goal is to display the data like this: { "payment_method": "test", "confirmation": "14087147WA285750M", "total_price": "15.00", "is_paid": "True", "order_created": "2021-07-09T19:51:18Z", "item_order": [ { "id": 2, "name": "Carrots", "image": "image link", "slug": "carrots", "price": "5.00", "itemID": "ct1", "quantity": 1 }, { "id": 8, "name": "Dog Food", "image": "image link", "slug": "dog-food", "price": "10.00", "itemID": "df4", "quantity": 1 } ] } View: @api_view(['POST']) def create_order(request): user = request.user order = request.data order_item = OrderModel.objects.create( user=user, payment_method=order['payment_method'], confirmation=order['confirmation'], total_price=order['total_price'], is_paid=order['is_paid'], order_created=order['order_created'], item_order= """ The item model instance """ ) ordered_items = OrderSerializer(order_item, many=True).data return Response(ordered_items) Order Model: class OrderModel(models.Model): user = models.ForeignKey(CustomerModel, on_delete=models.CASCADE) item_order = models.ForeignKey( ItemModel, on_delete=models.CASCADE) payment_method = models.CharField(max_length=50) confirmation = models.CharField(max_length=255) total_price = models.DecimalField( max_digits=5, decimal_places=2) is_paid = models.BooleanField(default=False) has_been_sent = models.BooleanField(default=False) order_created = models.DateTimeField() def __str__(self): return str(self.id) Order Serializer: class OrderSerializer(serializers.ModelSerializer): item_order = ItemSerializer(many=True) class Meta: model = OrderModel fields = ['payment_method', 'confirmation', 'total_price', 'is_paid', 'has_been_sent', 'order_created', … -
Crispy FormHelper object has no attribute 'attrs'
My views: class OrderCreate(CreateView): model = Order template_name = 'order_create.html' form_class = orderForm object = None def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) orderDetailform = orderDetailForm() return self.render_to_response( self.get_context_data(form=form, orderDetailForm=orderDetailform, helper=orderDetailFormHelper() ) ) def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) orderDetailform = orderDetailForm(self.request.POST) if form.is_valid() and orderDetailform.is_valid(): return self.form_valid(form, orderDetailform) else: return self.form_invalid(form, orderDetailform) def form_valid(self, form, assignment_question_form): """ Called if all forms are valid. Creates Assignment instance along with the associated AssignmentQuestion instances then redirects to success url Args: form: Assignment Form assignment_question_form: Assignment Question Form Returns: an HttpResponse to success url """ self.object = form.save(commit=False) # pre-processing for Assignment instance here... self.object.created_by = self.request.user self.object.save() # saving AssignmentQuestion Instances orderDetailforms = orderDetailForm.save(commit=False) for aq in orderDetailforms: # change the AssignmentQuestion instance values here # aq.some_field = some_value aq.save() content = {"name": self.object.created_by, "id": self.object.pk} send_gmail_message(['philippe@gustafoods.com', 'doro@gustafoods.com'], content) return reverse_lazy("procurement:order_detail", kwargs={'pk': self.object.pk}) forms.py: class orderDetailFormHelper(FormHelper): … -
Save card id to model on form submission
I want to save the stripe payment method id to my order when it's created for recurring orders. When using a previously saved card, it works as intended saving a "card_idxxxxx" which references a stripe payment method. Currently if the new card is input, it saves as "add-new-card", which is wrong. I would like it to save the newly input card to the customer, and also to the payment method field. What I'm mostly unsure about is: Why my card isn't saving to the customer in stripe How can I pass the new card's id to my view? template <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()"> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block uppercase text-gray-600 text-xs mb-2" for="card-element"> Card Details </label> <div id="card-element" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"> <!-- A Stripe Element will be inserted here. --> </div> <div id="card-result"></div> … -
Modifying oscarapi to show some endpoints as public from admin endpoints
What I am trying to achieve is to customize the oscarapi to expose the partner api to be public api instead of just for admin I have followed the docs on how to customize the api and also did as suggested by Jamie Marshall in Extending django-oscarapi API ROOT to custom API class So far I am able to overwrite the root.py file but failing to get oscar see the new urls.py file. My work so far is as follows I created a api_customization/views/partner.py file I created a api_customization/views/root.py file I tried to extend the urls.py file by creating a api_customization/urls.py file However, I'm getting the following error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, … -
Troubles with DeleteView in Django
recently I have been working on a board project for my courses. I wrote a DeleteView for a certain model. It worked for a while, and then it started giving me 404 error. Downbelow I will attach my code with the whole View and urls. PS: I know that I am not supposed to give all of that, but how knows, maybe you can help me with other mistakes)) Views.py class Post_list(LoginRequiredMixin, ListView): model = Post template_name = 'Post/list_of_posts.html' context_object_name = 'Posts' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(Post_list, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context class Post_details(LoginRequiredMixin, DetailView): model = Post template_name = 'Post/post_details.html' context_object_name = 'Post' class Post_create(LoginRequiredMixin, CreateView): model = Post template_name = 'Post/post_create.html' form_class = PostForm class Post_update(LoginRequiredMixin, UpdateView): template_name = 'Post/post_update.html' form_class = EditForm context_object_name = 'Post' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Post.objects.get(pk=ID) class Post_delete(LoginRequiredMixin, DeleteView): template_name = 'Post/post_delete.html' queryset = Post.objects.all() context_object_name = 'Post' success_url = '/Posts' def CategoryView(request, cats): category_posts = Post.objects.filter(cat=1) return render(request, 'Post/categories.html', {'cats': cats, 'category_posts': category_posts}) class Add_comment(LoginRequiredMixin, CreateView): model = Comments template_name = 'Post/add_comment.html' form_class = CommentForm success_url = '/Posts' def … -
'ManyToManyDescriptor' object has no attribute 'filter in Django while trying add item to favorite
Can someone please help me? I'm getting this error while I'm trying to change the icon color when added to favorites. Is there any solution for this error? This is the view where I'm adding my post to Favorite: @login_required def favourite_post(request, id): post = get_object_or_404(Car, id=id) if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) else: post.favourite.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) This is my Model class Car(models.Model): favourite = models.ManyToManyField(User, related_name='favourite', blank=True) And this where I want to send is_favourite bool which show is added to favorite or not def show_all_car_page(request): filtered_cars = CarFilter( request.GET, queryset=Car.objects.all() ) paginator = Paginator(filtered_cars.qs, 3) page = request.GET.get('page', 1) posts = paginator.get_page(page) is_favourite = bool if filtered_cars.Meta.model.favourite.filter(id=request.user.id).exists(): is_favourite = True context = { 'filtered_cars': filtered_cars, 'posts': posts, 'is_favourite': is_favourite } return render(request, 'index.html', context=context) And here CarFilter is my filter.py where i can filter my posts, class CarFilter(django_filters.FilterSet): class Meta: model = Car fields = ['brand', 'city', 'body_type', 'model', 'year', 'transmission'] And also in my template I'm doing like this : {% if request.user.is_authenticated %} <a href="{% url 'car:favourite_post' id=car.id %}" title="Seçilənlərə Əlavə et"> {% if is_favourite %} <i class="fas fa-heart" style="color: red"></i> {% else %} <i class="far fa-heart"></i> {% endif %} </a> {% else %} <a href="{% url 'user:login' %}" … -
Djanog, IntegrityError, NOT NULL constraint failed: ask_response.postinfo_id
I am new to Django and I have been following some YouTube tutorials to understand it's concepts. The website that I am creating is a blog/forum. Now I came to the part where I have to implement the comments for the user's posts, I created the model for the responses, and bonded it with the actual post. Everything works just fine when I add a response/comment for a specific post from the admin page, but when I try to add a new response/comment from the template form it gives me an error like this: IntegrityError at /question-1 NOT NULL constraint failed: ask_response.postinfo_id I assume it must be something about the form that doesn't want to work, but I cannot understand what. Here is the models.py: class PostInfo(models.Model): title = models.CharField(max_length=70) content = models.TextField(max_length=5000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) likes = models.ManyToManyField(User, related_name="blog_posts") views = models.IntegerField(default=0) class Response(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) postinfo = models.ForeignKey(PostInfo, on_delete=models.CASCADE, related_name="responses") body = models.TextField() date_published = models.DateTimeField(default=timezone.now) Views.py: def detailed_view(request, pk): post = get_object_or_404(PostInfo.objects.filter(id=pk)) comments = post.responses.all() new_comment = None if request.method == 'POST': comment_form = ResponseForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = ResponseForm() return render(request, … -
showing an attribute of a foreign key in admin for prepopulated_fields
Sorry for bad description of my issue in title ... I tried to find solution here with some answers but none helps me :( Here is my admin.py (a piece of) @admin.register(Espece) class EspeceAdmin(admin.ModelAdmin): list_display = ['nom', 'slug'] prepopulated_fields = {'slug': ('nom',)} [...] @admin.register(Produit) class ProduitAdmin(admin.ModelAdmin): list_display = ['nom', 'slug', 'prix', 'stock', 'stock_bis', 'available', 'espece', 'variete', 'portegreffe'] list_filter = ['available', 'prix', 'espece', 'portegreffe'] list_editable = ['prix', 'stock', 'available', 'stock_bis'] prepopulated_fields = {'nom': ('espece', 'variete', 'portegreffe', 'spec'), 'slug': ('nom',),} list_per_page = 200 search_fields = ('nom',) [https://ibb.co/TYCmk5Q][1] [1]: https://i.stack.imgur.com/SgfnN.png Thanks to link above, you'll see the issue on admin ... and my need When I choose a value in Select , I don't want to have the Id for espece into 'nom', but the value of espece... I don't know how to do this... And for my best exp, if it's possible ... after having good value, I need to prepopulated slug like nom but in slug format ;) Thanks for your help -
django multiple database migrations:how to prevent to create django default tables in each database
i have multiple databases and each app bind to one database through router class class DatabaseRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ lawyer_app_labels = {'lawyer'} court_app_labels = {'court'} type_app_labels = {'type'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.lawyer_app_labels: return 'lawyer_db' if model._meta.app_label in self.court_app_labels: return 'court_db' if model._meta.app_label in self.type_app_labels: return 'type_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.lawyer_app_labels: return 'lawyer_db' if model._meta.app_label in self.court_app_labels: return 'court_db' if model._meta.app_label in self.type_app_labels: return 'type_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.lawyer_app_labels or obj2._meta.app_label in self.lawyer_app_labels ): return True if ( obj1._meta.app_label in self.court_app_labels or obj2._meta.app_label in self.court_app_labels ): return True if ( obj1._meta.app_label in self.type_app_labels or obj2._meta.app_label in self.type_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in the 'auth_db' database. """ if app_label in self.lawyer_app_labels: return db == … -
when you enter an input field, throws an error although the whole model is correct. Python django
the form does not pass validation and throws an error, although the correct data is entered, what is the problem? I enter in the input field +79211234569 and gives an error in html Select the correct option. Your option is not among the valid values. form data: <'form': <RelatedAddForm bound=True, valid=False, fields=(name;phone)> forms class ListTextWidget(forms.Select): template_name = 'include/_forms_clients_datalist.html' def format_value(self, value): # Copied from forms.Input - makes sure value is rendered properly if value == '' or value is None: print('ListTextWidget None') return '' if self.is_localized: print('ListTextWidget local') return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class RelatedAddForm(forms.ModelForm): phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')) class Meta: model = Clients fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'}), } models class Clients(models.Model): name = models.CharField(max_length=150, blank=True, verbose_name='Имя') phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], unique=True, max_length=17, verbose_name='Телефон') def get_absolute_url(self): return reverse('view_clients', kwargs={'pk': self.pk}) def __str__(self): return self.phone -
Integrate Google Search Console API with Django Project
I am looking to integrate Google Search Console API with a Django project to fetche a list of sites verified in the site Search Console account and list any sitemap files submitted. I found this resource, but I am not sure how to use in the Django framework. Where should I place these functions and imports? https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python -
Nginx return 404 with vue router in second level path when press F5
Here the nginx config. server { listen 80; server_name server_ip; location = /favicon.ico { access_log off; log_not_found off; } error_page 404 /index.html; location /static/ { root /home/demo; } root /var/www/html/edu_vue/dist; index index.html; location / { try_files $uri $uri/ /index.html; } location ^~ /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /admin { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When i visis http://example.com/path and press F5 to reload everything is ok. But if path will be http://example.com/path/some_nested_path i'll get 404 from ngingx. Using Django Drf + Vue js + Vue Router in history mode true -
How to implement the add/edit links on a field in the admin change page that does not have an expressed FK relationship in the model?
I have a Django 3.x web site. There are 3 models, among others, Document, MetaData, MetaDataValue. The MetaDataValue model has a foreign key relationship to the MetaData model. In a simple world, there would be a foreign key relationship from MetaData to Document. Then the DocumentAdmin would display the MetaData field as a dropdown, filled with the appropriate MetaDataValues. There would also be edit/add (pencil/plus) links next to the dropdown to allow the user to edit/add the MetaDataValue for that MetaData object. However, one of the requirements for the project was not to define which, or how many, MetaData objects would be associated with a particular Document type until run time. Those associations are through another set of models. Therefore, the Document admin change page adds the different MetaData fields to the change admin page at run time, by looking into the database for which MetaData fields are associated with this type of Document, and then adding them to the fieldset through the get_fieldsets method. The implication of this design is that one cannot edit/add values to a particular MetaData field on the Document admin change page, because, I assume, Django lost the underlying foreign key relationship between the Document … -
Django many 2 many through rest framework
I am working on a small project but i cant get the serializers to work I have tried these and i am not sure what i am doing wrong. My model is a many to many through #serializers.py class CompanyVisitedSerializer(serializers.HyperlinkedModelSerializer): company_id = serializers.ReadOnlyField(source="company.id") company_address = serializers.ReadOnlyField(source="company.business_address") company_name = serializers.ReadOnlyField(source="company.business_name") company_address = serializers.ReadOnlyField(source="company.business_address") checked_in = serializers.ReadOnlyField(source="user.checked_in") checked_out = serializers.ReadOnlyField(source="user.checked_out") class Meta: model = CompanyUser fields = ( "checked_in", "checked_out", "company_name", "company_address", "company_id", ) class VisitorSerializer(serializers.ModelSerializer): # visited = CompanySerializer(many=True) visited = CompanyVisitedSerializer( many=True, ) ``` but i get this back empty {}: { "address": "192 millie road", "city": "singapore", "phone": "2066980", ... "visited": [ {}, //i want to populate this with { company: name_of_company, checkin, checkout} {} ] } I have read through these: https://bitbucket.org/snippets/adautoserpa/MeLa/django-rest-framework-manytomany-through Django: Serialize a model with a many-to-many relationship with a through argument -
How to Create and Use New Database for Neo4j Unit Test?
For my Django REST project, I need to perform unit test on my neo4j database to ensure the data outputted is in the correct format. However, I must perform these unit test on a testing database that is different than the actual database. Currently the settings.py is arranged in such a way that the views.py will access the default database. How can I have the Unit test access the test database instead without changing the settings.py? -
What the heck is this programming? [closed]
Firstly I started with java and learnt a bit code and after sometime I say programming career guide videos on Youtube. Someone said C++ is nice or someone said Java and Javascript. Some days later I selected Python for my programming language as it is easy for beginners and can be used in many fields e.g., Machine learning, Web-development, Android or Desktop development and even in hacking (I love Hacking @_@). I started with web-development. I didn't learnt completely and someone other developer said if you want to develop a webapp you'll also have to learn HTML, CSS, Javacript (The language, I hate the most) and also framework like Django. I thought Ohhh..! Ok, What the hell is this. I left taking all tutorials, I was following because of all of that worries, How I'll do this and who'll teach me and stuff like that. After some days I realize its ok man you can do it. I started again and after facing many problems as learnt all from Youtube because I don't have enough money to buy courses. Now with the thank of GOD, I created a web app using Django, HTML, CSS and a little bit of JS … -
How can I pass a string into a the .close() method of the FileResponse object?
I am altering the behavior of the .close() method of the FileResponse object. FileResponse is a subclass of StreamingHttpResponse which is very similar to the HttpResponse object. What I am trying to do is take a string of text, save it into a .docx, send that docx to the browser, then delete that docx. Everything is working great until I try to delete the .docx. It doesn't look like I can delete the file before the response is sent because the response needs the file, but I can't do anything at all after the response has been sent because the view has completed its task and sent a response. A potential solution I have found is to modify the .close() method of the FileResponse object (similar to the HttpResponse object) to delete the file. Great. However, I do not know how to pass the path to the file to the .close() method. This might be an elementary question, but I generally avoid editing built in class methods. Code below. import logging from django.http import FileResponse import os logger = logging.getLogger("django") #editing the default closing behavior of the file response object to delete the file that it just sent. class SendAndDeleteExport(FileResponse): … -
Django Python Makemigrations and Runserver do Nothing
I downloaded a .zip template from github of a blog web app built in django and am trying to deploy it to my local server... I have tried running the following lines in my command line, but am not getting any response back... nothing happens except that it just moves to the next line. Any idea why this is occurring? I am able to create a new project using django, I am able to install requirements via command line, and I can run other python scripts fine. C:\Users\xxx>cd C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py runserver 8080 C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py makemigrations C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py migrate C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master> -
Django Cors Headers settings not working with vue and axios
This is my settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8000", "http://192.168.225.206:8080" ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES' : ( 'rest_framework.permissions.IsAuthenticated', ) } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'apps.client', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] at least where rest_framework is set. This is my main.js from <vue_project>/src import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import axios from '../node_modules/axios' axios.defaults.baseURL = 'http://127.0.0.1:8000' createApp(App).use(store).use(router, axios).mount('#app') But when I tried this code which is clients.vue <script> import axios from 'axios' export default { name: 'Clients', data(){ return { clients: [] } }, mounted(){ this.getClients(); }, methods: { getClients(){ axios.get('/api/v1/clients/') .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common["Authorization"] = "Token" + token localStorage.setItem("token", token) for(let i = 0; i < response.data.length; i++){ this.clients.push(response.data[i]) } }) .catch(error => { console.log(JSON.stringify(error)) }) } } } </script> I get a Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/clients/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authoriaxation is not allowed by Access-Control-Allow-Headers in preflight response. Then I checked if I get the same … -
Deploying Django App on Heroku. While Pushing the App on heroku it gives the error
My Django App working well in localhost, but when I am pushing it on the Heroku by using the Git Bash terminal, the following error is shown. What is GCC?. Why these errors are showing up while deploying it on Heroku. Is there any library missing? remote: Building wheel for pyyaml (setup.py): started remote: Building wheel for pyyaml (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qb9qpcl0/pyyaml/setup.py'"'"'; __file__='"'"'/tmp/pip-install-qb9qpcl0/pyyaml/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-s5u8j4v7 remote: In file included from /app/.heroku/python/include/python3.9/unicodeobject.h:1026, remote: from /app/.heroku/python/include/python3.9/Python.h:106, remote: from ext/_yaml.c:4: remote: /app/.heroku/python/include/python3.9/cpython/unicodeobject.h:446:26: note: declared here remote: 446 | static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) { remote: | ^~~~~~~~~~~~~~~~~~~~~~~~~~ remote: error: command '/usr/bin/gcc' failed with exit code 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pyyaml remote: Running setup.py clean for pyyaml remote: Building wheel for strict-rfc3339 (setup.py): started remote: Building wheel for strict-rfc3339 (setup.py): finished with status 'done' remote: Created wheel for strict-rfc3339: filename=strict_rfc3339-0.7-py3-none-any.whl size=18119 sha256=169b25d50478fa157faaa6b19e8714b42c42c771ca6926bb2d728a8fe20e9be8 remote: Stored in directory: /tmp/pip-ephem-wheel-cache-wyzbci7g/wheels/25/38/74/7ec7f77ec64b2907430120931ba588b40e6e26f02d4df5be35 remote: Building wheel for Kivy-Garden (setup.py): started remote: Building wheel for Kivy-Garden (setup.py): finished with status 'done' remote: Created wheel for Kivy-Garden: filename=Kivy_Garden-0.1.4-py3-none-any.whl size=4532 … -
trying to run django server but ip and port is not showing up after this statement
python manage.py runserver Watching for file changes with StatReloader it is a projext ive downloaded from my git acconunt -
Creating User using Djoser is not storing data for all fields (
I am using DRF to create a ReST API. I am using Djoser for user management. I am using the default django user model as it serves my purpose. When I hit the endpoint to register new user, only username, password and email are getting stored. I am passing all data like first_name, last_name and is_staff but only username, password and email are being stored. I have attached Djsoer settings. DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'USER_CREATE_PASSWORD_RETYPE': True, #Designed to propote good programming practice 'SET_PASSWORD_RETYPE': True, #Designed to propote good programming practice 'PASSWORD_RESET_CONFIRM_RETYPE': True, #Designed to propote good programming practice 'LOGOUT_ON_PASSWORD_CHANGE' : True, #Note : Logout only works with token based authentication. djoser 2.10 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system 'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system 'token': 'djoser.serializers.TokenSerializer', 'token_create': 'djoser.serializers.TokenCreateSerializer', } What I am doing wrong? -
Django nested if statement giving me a strange error
I have 2 if statements right next to each other to check for to see if a user is following another user. I am getting a weird error when I attempt to close both of the if statements. I have a block content and endblock at the top and bottom of the page. I also have a load humanize tag. I have attempted to add a endblock tag and I tried reshuffling things around. I am kinda stuck but I know I'm forgetting something. Can any help me out? Here is the code <h1 class="title">{{ request.user.username }}</h1> <p>Followers: {{ user.foxyprofile.followed_by.count }}</p> <p>Follows {{ user.foxyprofile.follows.count }}</p> {% if user != request.user %} {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %} <a href="{% url 'unfollow_foxy' user.username %}" class="button is-danger">Unfollow</a> {% else %} <a href="{% url 'follow_foxy' user.username %}" class="button is-success">Follow {{ user.username}}</a> {% endif %} {% endif %} and the error I'm getting... Invalid block tag on line 17: 'endif', expected 'endblock'. Did you forget to register or load this tag?