Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does one count a foreign key item, esp 'author' created with Django's User model?
Need help getting a better grip with 1) accessing and counting foreign key items in Django and 2) counting foreign key item that is created through Django's built-in User: #1) The answer here suggests using Django's annotate function: eg. questions = Question.objects.annotate(number_of_answers=Count('answer')) (question being a foreign key item to answer). But it is not clear to me where this line belongs to (in the case of the example, question or answer), or which part of an app-models.py or views.py. I tested in both models.py and views.py Here are my models (only the essential lines here): class Post(models.Model): post = models.TextField(max_length=1000) author = models.ForeignKey(User, related_name="author", on_delete=models.CASCADE) class Comment(models.Model): comment = models.TextField(max_length=1000) commenter = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE, default=None, null=True) #2) How does one access a foreign key item created using Django's built-in model, User? Should I have created a model called "Author" first? -
How do I make the django admin site rely on my custom Django Rest Framework Token Authentication?
Throughout development of my application, the authentication has worked great. Using DRF I overrode DRF's TokenAuthentication to provide an expiring token, and then overrode ObtainAuthToken to create the authentication post request view. Now I'm trying to launch the application into production with DEBUG=False. The application seems to be running fine, but the django admin site will not let me log in to my super user (yes I created it with createsuperuser and have verified it exists in the database). The error I get back is: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This confused me because I'm using Token authentication and not Sessions. In my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'custom_auth.authentication.ExpiringTokenAuthentication' ] } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I believe the django.middleware.csrf.CsrfViewMiddleware was put in there by default when I created the application, and I assume this … -
customer Select a valid choice. That choice is not one of the available choices
please i want someone to help me solve this problem. if there's a better way i can write the codes, i will really appreciate. what i want is for the user to make order and get redirected to a page where the user will see all his orders . please someone should help out error message : customer Select a valid choice. That choice is not one of the available choices client model file from django.db import models # Create your models here. class ClientJob(models.Model): STATUS = ( ('Pending', 'Pending'), #('On-going', 'On-going'), ('Completed', 'Completed'), ) customer = models.ForeignKey('accounts.Customer', null=True,blank=True, on_delete= models.SET_NULL,related_name='client') job_name = models.CharField(max_length=50,unique =False) text_description = models.CharField(max_length=150,null=True) location = models.ForeignKey('accounts.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200,unique =False) phone =models.CharField(max_length=15,unique =False) email = models.EmailField(unique = False) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS,default='Pending') def __str__(self): return self.job_name class Meta: verbose_name_plural = "Client Job" client forms.py file from django.db.models import fields from django.forms import ModelForm from django import forms from django.contrib.auth.models import User from .models import * class ClientJobForms(ModelForm): class Meta: model = ClientJob fields = ['job_name','text_description','location','address','phone','email','status','customer'] #fields ="__all__" def __init__(self, *args, **kwargs): super(ClientJobForms, self).__init__(*args, **kwargs) self.fields['location'].empty_label ='Your location' client admin file from django.contrib import admin from .models import … -
SimpleJwtAuthentication django
Does simplejwt authentication works with custom user model .if not ,is there any way to achieve. models.py class user_model(models.Model): username=models.CharField(max_length=200,blank=True,unique=True) email=models.CharField(max_length=200,blank=True) password=models.CharField(max_length=200,blank=True) age=models.CharField(max_length=200,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username -
Is there a way to submit multiple forms with a single button and unique hidden values?
Note: I have seen some posts that are quite similar to mine but I don't think those solutions help in my use case. My website (made using Django) has a page for collecting dues payments. There is one page per family, in which there will be multiple dues to be paid by each member. Currently, I have one submit button to each due as you can see in the code below. {% for due in dues %} <tr> <td>{{due.0}}</td> <td>{{due.1}}</td> <td>{{ due.3}}</td> <td>{{ due.4 }}</td> <td>{{ due.5 }}</td> <td><form action="/dues/?family-dues={{ familyprofile }}" method="POST" id= "dues-payment"> {% csrf_token %} <input type="text" placeholder="Enter Amount" name="amount"> <input type="hidden" value="{{due.2}}" name="due-id"> <input type="hidden" value="{{due.0}}" name="member-id"> <input type="hidden" value="{{duefamily.0}}" name="family-id"> <button id="submit-payment">Pay</button></form></td> </tr> {% endfor %} The issue with this is that, only one payment can be done at a time. Is there a way where I can instead submit all the forms in one go. So that the cashier can just enter the appropriate payments in each textbox and when its submitted all the textbox values(paid amount) along with the due id be returned in one go? Current Scenario Due ID 1 textbox(Value is 40) Pay Button Due ID 2 textbox(Value is 80) Pay … -
How can I access an attribute of a model which is a foreignkey to another model in the views.py file
For example I have two models .Brand model which is a foreign key to another model Item. The Brand model has an attribute best_seller which is a boolean field recording whether a certain brand of items is a best seller. In my views I want to filter only the items whose brand is a best seller.How can I do this This is how my models.py looks like class Brand(models.Model): title = models.CharField(max_length=100) best_seller = models.BooleanField(default=False) def __str__ (self): return self.title class Item(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) new_price = models.DecimalField(max_digits=7, decimal_places=2) image = models.ImageField(upload_to='static/images') old_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) slug = models.SlugField() description = models.TextField() featured = models.BooleanField(default=False) def __str__ (self): return self.title Then this the views.py file def home(request): brand = Brand.objects.filter(best_seller=True) bests = Item.objects.filter(brand=True).order_by('-id')[:12] context = { 'items': items, 'bests': bests } return render(request, 'home.html', context) After doing this there's nothing being rendered on the browser -
Nested fields/objects creation with DRF
It's me again with questions about the polls API I'm working on. I have three models: Poll, Question and Choice. from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Poll(models.Model): title = models.CharField(max_length=200, verbose_name="Naslov ankete") description = models.TextField(verbose_name="Opis ankete") author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor") pub_date = models.DateTimeField(auto_now_add=True, verbose_name="Datum objavljivanja") class Meta: ordering = ["pub_date", "title"] verbose_name = "Anketa" verbose_name_plural = "Ankete" def __str__(self): return self.title class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa") question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja") class Meta: # ordering = ["question_text"] verbose_name = "Pitanje" verbose_name_plural = "Pitanja" def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje") choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije") votes = models.IntegerField(default=0, verbose_name="Glasovi") class Meta: # ordering = ["-votes"] verbose_name = "Opcija" verbose_name_plural = "Opcije" def __str__(self): return self.choice_text Whatever I put in the serializers, I can't achieve the creation of questions and choices at the same time with the poll. How should my serializers look like if I want to use the following JSON, but still be able to create questions and choices independently? { "title": "Favorite destinations", "description": "A few questions about traveling", "questions": [ {"question_text": "Which destination seems better for you?", "choices": [{"choice_text": "London"}, {"choice_text": … -
admin-path is removed from url, but can still be accessed (Django)
I have a django application of which I want to remove the Admin-access in production. Because of that I've removed the admin-url from the url.py file, but if I go to myapp.com/admin/login it still allows me to log in. Is there a way to disable admin-login in production?` -
Django Changing HTML Template Not Reflecting
I'm new to Django, I have created a webportal and recently came to know their is an issue in the portal. After changing the html content, its not reflecting the content in portal, still displaying old html data. Could someone please tell me, what needs to be done. Note: I have reloaded django from command prompt and verified, but getting the same issue, Thank You!! -
Merging a field in one model to another with ForeignKey, Django Subquery and OuterRef
I have two models, RetailLocation and Transaction, which share a one-to-many relationship respectively. My goal is to annotate RetailLocation with the date of the latest Transaction which corresponds to that RetailLocation. The model Transaction includes "r_loc_name" which is the exact same string as RetailLocation.name. I believe this field is redundant, and I expect there is a better solution using only the r_loc ForeignKey (and set) in RetailLocation, however I have not figured out how. Models class RetailLocation(models.Model): name = models.CharField(max_length=200, null=True) class Transaction(models.Model): date = models.DateTimeField(null=True) r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL) r_loc_name = models.CharField(max_length=200, null=True) # Likely redundant Attempted Code loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Subquery( Transaction.objects.filter(r_loc_name=OuterRef("name")) .order_by("date") .values("date") .last() ) ) Another Attempt loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Value( Subquery( RetailLocation.objects.get(name=OuterRef("name")) .transaction_set.order_by("date") .last() .date ), DateTimeField(), ) ) My goal is to to reference RetailLocation.latest_txn_time, which would be the annotated datetime of the latest Transaction referenced to that RetailLocation. Thank you very much -
How do I get the data send by Ajax in Django?
I tried to get the data I send via Ajax with request.GET.get, but this does not work. Data is always None. I really appreciate any kind of help! This is my jQuery/Ajax code: $(document).ready(function(){ $(".jcf-select.jcf-unselectable").on('click', function(){ var sel = $('#sort').children("option:selected").val(); console.log(sel) $.ajax({ url: '/filter-data', data: sel, dataType: 'json', success:function(res){ console.log(res); $("#filter_products").html(res.order); } }); }); }); This is my view: def filter_data(request): if request.is_ajax: query = [] data = request.GET.get('data') if data == "gpv": query = data.order_by("price_with_shipping")[:150] elif data == "gp": query = data.order_by("lowest_price")[:150] elif data == "lp": query = data.order_by("liter_price")[:150] elif data == "tz": query = data.order_by("-lowest_price")[:150] t = render_to_string('homepage/ajax-products.html', {'order': query}) return JsonResponse({'order': t}) -
Cannot create django project in cmd
when I want to start a project with Django in cmd. I got an error. please I need help -
How do i pass a django url parameter to redirect function
I'm creating a blog website and I want it to be that when a user update a post, I want to redirect them to the view page for that article. the urls.py url_patterns = [ path('view/<str:id>/, views.viewPost, name='viewpost'), path('update/<str:id>/, views.updatePost, name='updatepost') ] My problem is that, I want to be able to redirect to the viewpost when I update a post I tried return redirect('viewpost' id) But it was giving me an error Thanks for your contribution -
Django SearchFilter Multiple models
Using Django 3.2 with Restframework. I'm trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: Views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar,section,item)) print(all_results) #Objects as output are printed in console return all_results #Blank output serializers.py class GlobalSearchSerializer(serializers.Serialize): def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data In here, while printing the output it does print objects, but doesn't return anything as output. Any cause why there is no output, where am I doing wrong? Also I tried with serializers.ModelSerializer but … -
Why Django unique constraints did not work?
I've added UniqueConstraint into the constraints array in the Meta class which is a subclass of User table. class User(AbstractBaseUser): ... class Meta: verbose_name = _("account") verbose_name_plural = _("accounts") indexes = [ models.Index(name="email_index", fields=["email"]) ] constraints = [ models.CheckConstraint(name="check_birth_date", check=Q(birth_date__lt=f"{datetime.date.today()}")), models.CheckConstraint(name="check_phone_number", check=Q(phone_number__regex=r"^09(1[0-9]|2[0-9]|3[0-9])[0-9]{3}[0-9]{4}$")), models.UniqueConstraint(name="username_email_unique", fields=["username", "email"]) ] My expectation was that prevent user to enter username and email with same value, But actually did not work and user can do it without getting the IntegrityError Moreover, I'm using Postgresql -
how to put multiple Forms in the same views.py - Django
I need to put four Form in one views.py function, but I have no idea how to do it. I need every form to show on the site on the same time. I will take any advice on how I can solve this problem. models.py # Hotel class Hotel(models.Model): customer = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/',default="images/default.jpg" , blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) # Room class Room(models.Model): hotel = models.ForeignKey(Hotel, null=True, on_delete=models.CASCADE) def __str__(self): return f'Room of {self.hotel}' # Single type for Room class Single(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_single_room', 'Budget Single Room'), ('Standard_single_room', 'Standard Single Room'), ('Superior_single_room', 'Superior Single Room'), ('Deluxe_single_room', 'Deluxe Single Room'), ) name = models.TextField(max_length=30, choices=ROOM_NAME, null=True) ROOM_SMOKE = ( ('Smoking', 'Smoking'), ('Non-Smoking', 'Non-Smoking'), ) smoke = models.TextField(max_length=15, choices=ROOM_SMOKE, null=True) bed = models.IntegerField() capacity = models.IntegerField() room_size = models.IntegerField() def __str__(self): return f'{self.name}' # Double type for Room class Double(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_Double_room', 'Budget Double Room'), ('Standard_Double_room', 'Standard Double Room'), ('Superior_Double_room', 'Superior … -
DRF changes name or ignores "create" route
I'm new to DRF's "viewsets", but I've inherited some problematic code, and am having trouble figuring out what's going on. I have stripped down the code below to isolate the behavior I don't understand. In my urls.py I have from my_app.api import CurrentUserViewSet, from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("me", CurrentUserViewSet, basename="api-me") print(router.urls) Note the diagnostic print statement at the end. The CurrentUserViewSet is defined as: from rest_framework import viewsets from django.views.generic import View class CurrentUserViewSet(viewsets.ViewSetMixin, View): def create(self, request): """Update current user.""" instance = request.user ... @action(detail=False, methods=["post"]) def some_other_route(self, request): ... When I start a runserver instance that uses the above, it hits my print statement in "urls.py" and displays this: [ <URLPattern '^me/$' [name='api-me-list']>, <URLPattern '^me\.(?P<format>[a-z0-9]+)/?$' [name='api-me-list']>, <URLPattern '^me/some_other_route/$' [name='api-me-some-other-route']>, <URLPattern '^me/some_other_route\.(?P<format>[a-z0-9]+)/?$' [name='api-me-some-other-route']>... ] So it looks like the name of my create route is being changed to list. I don't know how or why this is happening. Interestingly, if I define an addtional route that is actually named "list", the "create" method still does not appear in the URLs created by the router. It seems to be totally ignored. As I mentioned, I inherited this code. I think that even though the original author named … -
Django - Firebase real time chat system
I need to make a chat system between a django app and an android app via a firebase real time database. I am using Pyrebase4 for handling the firebase, and Channels to handle the socket connection. I have a listener that listens to any changes in the chat room inside the Firebase real time database The listener is activated when the page is loaded: from accounts.firebase_repo import db def listen_to_chat(request, patient_key): doctor_id = request.user.id chat_id = f"{patient_key}_{doctor_id}" db.child("Chats").child(chat_id).stream(stream_handler) The stream_handler callback: def stream_handler(event): acc = AsyncChatConsumer() asyncio.run(acc.receive(event['data'])) The AsyncChatConsumer class: class AsyncChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, message): pass async def receive(self, text_data=None, bytes_data=None): # json_to_send = {} if text_data is not None: if 'message' not in text_data: # this is triggered on page load. Fetches all of the messages inside the room await self.send(text_data) else: # this is triggered when a new message is posted in the Firebase await self.send(text_data) the send method should trigger my javascript code. I have a chatSocket that I initialize when the DOM is loaded: window.addEventListener('DOMContentLoaded', (event) => { initializeSocket( "{{ context.key }}", "{{ context.doctor_id }}", "{% url 'send_message' %}" ); }); chatSocket = new WebSocket(wsStart + loc.host + '/ws/chat/' + … -
Django TypeError: get() got an unexpected keyword argument 'quiz_name'
I am trying to access a url from flutter webview , however, I am getting the following error. When I try to access this directly, I dont see any error. File "/home/quiz/views.py", line 629, in dispatch return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) TypeError: get() got an unexpected keyword argument 'quiz_name' views.py class QuizTakeAutoAuth(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied if self.sitting is False: print("sitting false") if self.logged_in_user: return render(request, self.single_complete_template_name) else: redirecturl = "/login/?next=/quiz/"+self.kwargs['quiz_name']+"/take/" return redirect(redirecturl) return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) urls.py url(r'^(?P<quiz_name>[\w-]+)/startquiz/$',view=QuizTakeAutoAuth.as_view(), name='quiz_question_auth'), What am I missing here? I am using the same view elsewhere without any knox Tokenauthentication and works as expected. -
Post working from build-in rest_framework UI (in browser) but not from Postman
while starting my backend project I've run into a problem and can't find a solution. I work with django and wanted to implement crud operations for one table named tutorials and these operations run great when I use the browser or build-in rest_framework UI from the browser but when I try the post request from postman (sending a json object) it gives me the 500 internal server error from postman this is my project structure , I have only one app called platforme : project structure This is the code in platforme/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from platforme import views urlpatterns = [ path('tutorials/',views.TutorialList.as_view()), path('tutorials/<int:pk>/',views.TutorialDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) This is the code in platforme/models.py , I only have one model from django.db import models # Create your models here. class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) This is platforme/serializers.py from rest_framework import serializers from platforme.models import Tutorial class TutorialSerializer(serializers.ModelSerializer): class Meta: model = Tutorial fields = ('id','title','description','published') And finally this is the platforme/views.py : from rest_framework import generics from rest_framework import mixins from platforme.models import Tutorial from platforme.serializers import TutorialSerializer class TutorialList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Tutorial.objects.all() serializer_class … -
Docker files to be ignored on .gitignore
I'm new to docker. I've finalized dockerizing a Django projet of mine. What files and/or folders should I add to my .gitginore before pushing the changes to the project? Or no files should be added? I'm not talking about my .dockerignore file. -
Django migrations problem: Field id expectet a number but got 'China'
I set a default value of Country field in Item model as 'China'. Then i tried migrate and i showed an error that should set a default value in each of field. I've done it but after next migrate command i got an error "Field id expecter a number but got 'China'", but i change a default value to '4'. P.S.: I don't use Model.objects.filter() anywhere. I just work with models only. It's my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from slugger import AutoSlugField class Item(models.Model): title = models.CharField(max_length=128) price = models.DecimalField(max_digits=7, decimal_places=2, default='0') color = models.ForeignKey('Color', on_delete=CASCADE, default='White') category = models.ForeignKey('Category', on_delete=CASCADE, default='SOMECATEGORY') age = models.ForeignKey('Age', on_delete=CASCADE, default='0') description = models.CharField(max_length=5000, default='') in_stock = models.BooleanField(default=True) country = models.ForeignKey('Country', on_delete=CASCADE, default='4') # here was default value China slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Color(models.Model): color = models.CharField(max_length=32) def __str__(self): return self.color class Category(models.Model): category = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.category class Country(models.Model): country = models.CharField(max_length=64) class Meta: verbose_name_plural = 'Countries' def __str__(self): return self.country class Age(models.Model): age = models.CharField(max_length=32) class Meta: verbose_name_plural = 'Ages' def __str__(self): return self.age -
How to export python list into excel file using xlwt?
Here I am trying to export python list to the excel file but it is not working correctly. The list will be dynamic. response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="excle_file.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('datas', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['col1', 'col2', 'col3', 'col4', 'col5'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = [20, Decimal('50000.00'), Decimal('10.00'), Decimal('40000.00'), Decimal('90000.00'), 21, Decimal('31000.00'), Decimal('2000.00'), Decimal('41000.00'), Decimal('74000.00')] for i,e in enumerate(rows): ws.write(i,1, e) wb.save(response) return response I want response like this. col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 2000 41000 74000 Current response col1 col2 col3 col4 col5 20 50000 10 40000 90000 21 31000 .... Also I want to increase the size of the column based on the text? How it will be done ? -
How to add javascript variable to django model database
I want to insert this javascript variable into django model which look like this. It's a location info variable which has address, latitude, longitude and place name. placeInfo = { address: "address example" latlng: pa {La: 51.12508408777138, Ma: 1.3337612324096222} name: "name example" } The database model consists of Posts model and Place model is subordinated to the Posts model. I want to put placeInfo javascript variable to the Place model. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) lat = models.CharField(max_length=25) lng = models.CharField(max_length=25) def __str__(self): return "{}".format(self.name) class Posts(models.Model): title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="location") def __str__(self): return str(self.title) What I've searched until now is about AJAX handling but I'm not used to it so any help would be appreciated -
Getting ModuleNotFoundError in Django
Project Structure urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('login_user', views.login_user, name='login_user'), path('logout_user', views.logout_user, name='logout_user'), path('register_user', views.register_view, name='register_user'), path('dashboard', views.dashboard, name='dashboard'), ] chat_app2/views.py from django.contrib.auth import logout, authenticate, login from django.http import HttpResponse from django.shortcuts import render, redirect from chat_app2.account.forms import RegistrationForm def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect('homepage') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'register_user.html', context) settings.py AUTH_USER_MODEL = 'account.Account' # Application definition INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Error File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\urls.py", line 3, in <module> from . import views File "C:\Users\Manish Gusain\Documents\Python_Projects\chat_app2\chat_app2\views.py", line 4, in <module> from chat_app2.account.forms import RegistrationForm ModuleNotFoundError: No module named 'chat_app2.account' I'm trying to add new user to the database using a user …