Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with serializer and api
My problem is that I want to to get category.name instead of category.id in api. class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ['id', 'title', 'content', 'category', 'img', 'date_posted'] But when I adding it, there disappears option in POST method to set category. For api view I use generics.ListCreateAPIView def getCategory(self,obj): return obj.category.name category = serializers.SerializerMethodField("getCategory") -
NoReverseMatch at /register Reverse for 'activate' with keyword arguments '{'uidb64': 'MjA', 'token': 'b30qd1-7f95e1136cc4896c8b15fdc839486de
I have this code running for one project and not working for another project. def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): # save form in the memory not in database user = form.save(commit=False) user.is_active = False user.save() # to get the domain of the current site current_site = get_current_site(request) mail_subject = 'Activation link has been sent to your email id' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} def activate(request, uidb64, token): User = get_user_model() try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', activate, name='activate'), -
How to fill a Django form with an API response?
I need to create a form of persons, where the camp Name must receive an API response. I created the formulary e rendered the api response in template, but I can´t put it in my formulary, in order to save in my Models camp Name. So, I just want to save my API respone inside my forms and in my database. Views def cadastro(request): url = 'https://gerador-nomes.herokuapp.com/nome/aleatorio' api = requests.get(url) nome_api = ' '.join(api.json()) form = PessoaForm() form.nome = api if request.method == 'POST': form = PessoaForm(request.POST) if form.is_valid(): form.cleaned_data('nome') form.save() return redirect('/') context = {'form': form, 'api': nome_api} return render(request, 'base/pessoa_form.html', context) pessoa_form.html <body> <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" name="Cadastrar"> </form> </body> </html> Forms from django.forms import ModelForm from . models import Pessoa class PessoaForm(ModelForm): class Meta: model = Pessoa fields = '__all__' Models from django.db import models class Pessoa(models.Model): name= models.CharField(max_length=255, null=True) lastname= models.CharField(max_length=255, null=True) age= models.IntegerField(null=True) birthday_date= models.DateField() email = models.CharField(max_length=255, null=True) nickname= models.CharField(max_length=255, null=True, blank=True) note = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.nome class Meta: ordering = ['nome', 'sobrenome'] I have tried some things of my head but nothing actually worked, like try to access the variable Name in my forms … -
How to link between django views components
Actually, I am pretty new in Django. I have created three views in my views.py. This is my following code in views.py : from django.shortcuts import render import pymongo from .models import * from .serializers import * from .forms import * from .codes.scraping import scrap def home_view(request): context = {} context ['form'] = Scraping() return render(request,'home.html',context) def loading_view(request): return render(request,'loading.html') def datatable_view(request): client = pymongo.MongoClient("mongodb://localhost:27017/") db= client["aliexpress_db"] col = db["segment"] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) My question is that I want to get a method in order to get the home_view first then my loading_view while the scraping is processing then my datatable_view. I don't know how to link between these views. I am completely beginner. Any help would be great. -
React index.js in Django Project doesn't render imported components
I am trying to build a project with a hybrid architecture with Django as Backend and React as Frontend. For this I use Webpack and Babel to pipe the js files into djangos static index-bundle.js. However I encountered a problem which I don't understand. Apparently I can not import other components into my index.js react file. Instead, the root div stays empty. While this works and the text is visible in the Browser... ReactDOM.render( <h1> React in Django </h1> document.getElementById('root') ); ... importing it from another component doesn't work (div "root" has no inner elements) ReactDOM.render( <App />, document.getElementById('root') ); class App extends Component { render() { return ( <h1>React in Django</h1> ) } } In the end I want to have the "normal" react behaviour inside the django project. -
Test User logout in Django fails
I need to test if my user is logged out correctly. When I tried to logout, the test fails. def test_user_logout(self): """Test user logout.""" user = User.objects.create_user(username="test", password="test") self.logged_in = self.client.force_login(user=user) response = self.client.post(path=reverse("logout"), follow=True) self.assertEqual(response.status_code, 200) self.assertRedirects(response, reverse("login")) self.assertTrue(user.is_anonymous) # this fails My view method is: def user_logout(request): logout(request) return redirect("login") -
How do I make signup page avilable only for logged in staff users in Django allauth?
I'm very new to Django. I used allauth to make email verification and user management system simple. I want a system where only admins (staff users) can signup users. But as it is now signup page is only available for not logged in users. How do I make signup page available only for logged in staff users in Django allauth? -
display data without using a loop Django
how do I forgo the loop and display only one product represnted by {data.title }} {% for data in data %} <h3 class="my-4 border-bottom pb-1">{{data.title }}</h3> <div class="row"> {% endfor %} tried to use <h3 class="my-4 border-bottom pb-1">{{data.title }}</h3> <div class="row"> and got a blank section, the loop works perfectly though the views function booking_detail(request, slug, id): booking=Bookings.objects.all().order_by('-id') return render(request,'booking_detail.html',{'data':booking}) model class Bookings(models.Model): title=models.CharField(max_length=200) image=models.ImageField(upload_to="rooms_imgs") slug=models.CharField(max_length=400) detail=models.TextField() features=models.TextField() location=models.ForeignKey(Location, on_delete=models.CASCADE) category=models.ForeignKey(Category, on_delete=models.CASCADE) hostel=models.ForeignKey(Hostel, on_delete=models.CASCADE) amenities=models.ForeignKey(Amenities, on_delete=models.CASCADE) roomsizes=models.ForeignKey(RoomSizes,on_delete=models.CASCADE) status=models.BooleanField(default=True) is_featured=models.BooleanField(default=False) is_availabe=models.BooleanField(default=True) url path('booking/<str:slug>/<int:id>',views.booking_detail,name='booking_detail'), -
Django - How to use django signals in async consumer classes?
I want to send a web socket from a Django signal receiver in an asynchronous consumer. The code below results in an error: Object of type coroutine is not JSON serializable Consumers.py class MessagePreviewConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() last_message_general = await self.last_message_general() await self.send(text_data=json.dumps({ 'last_message_general': last_message_general, })) @sync_to_async def last_message_general(self): last_msg = Message.objects.filter(room = 'General')[len(Message.objects.filter(room = 'General'))-1::] if len(Message.objects.filter(room = 'General')) >= 1 else Message.objects.filter(room = 'General') if last_msg: for m in last_msg: result = m.content, m.author.username, m.date_added.strftime("%H:%M") return str(result) break else: pass @receiver(post_save, sender=Message) def message_preview(sender, instance, created, **krwargs): if created: print(sender, instance, created) last_message_general = MessagePreviewConsumer.last_message_general() MessagePreviewConsumer.send(text_data=json.dumps({ 'last_message_general': last_message_general, })) Question: How can I call this send function from the signal receiver? -
Get value from span to Django view
I have this javascript that gets longitude and latitude from a Google Map: <script> // Get element references var confirmBtn = document.getElementById('confirmPosition'); var onClickPositionView = document.getElementById('onClickPositionView'); var latonIdlePositionView = document.getElementById('latOnIdlePositionView'); var longonIdlePositionView = document.getElementById('longOnIdlePositionView'); // Initialize locationPicker plugin var lp = new locationPicker('map', { setCurrentPosition: true, // You can omit this, defaults to true }, { zoom: 15 // You can set any google map options here, zoom defaults to 15 }); // Listen to map idle event, listening to idle event more accurate than listening to ondrag event google.maps.event.addListener(lp.map, 'idle', function (event) { // Get current location and show it in HTML var location = lp.getMarkerPosition(); latOnIdlePositionView.innerHTML = location.lat; longOnIdlePositionView.innerHTML = location.lng; }); </script> This is the HTML I have for a user to define his or her location: <form method="POST" action="{% url 'geolocate' %}"> {% csrf_token %} <div class="card-header"> <div class="float-start"> <h3 class="card-title">Me localiser</h3> </div> </div> <div class="card-body no-padding"> <div id="map"></div> <p>Latitude: <span id="latOnIdlePositionView"></span> Longitude: <span id="longOnIdlePositionView" ></span></p> </div> <div class="card-footer text-end"> <button type="submit" class="btn btn-primary">Mettre à jour</button> </div> </form> This is my view: def geolocate(request): if request.method == 'POST': lat = request.POST.get('lat_kw') long = request.POST.get('long_kw') caccount = Account.objects.get(username=request.user.username) caccount.lat = lat caccount.long = long caccount.save() return redirect('monprofil') … -
Django i18n multi-line translate
How to translate the snippet below using django's internalization? utils.py template = _("Below is the result of your WWE Account verification.\n" "Thank you!") django.po # try msgid "Below is the result of your WWE Account verification.\nThank you!" msgstr "A continuación se muestra el resultado de la verificación de su cuenta WWE.\n ¡Gracias!" But when I do the code snippet below... $ python manage.py shell >>> from django.utils.translation import activate, ugettext_lazy as _ >>> activate('zh-cn') >>> template = _("Below is the result of your WWE Account verification.\n" "Thank you!") >>> template 以下是您的 WWE 帐户验证结果。\n谢谢 The above outout of template is wrong. I expected a new line like below: 以下是您的 WWE 帐户验证结果。 谢谢! or Below is the result of your WWE Account verification. Thank you! -
Django request.FILE returning None
My html template <form method="post" action="" enctype="multipart/form-data" class="form-group"> {% csrf_token %} <h1 class="m-3 text-center">New Post</h1> <div id="tui-image-editor-container" style="min-height:750px;"></div> <!--<input type="file" name="name" value="" />--> <div class="row m-2"> <input type="datetime-local" class="form-control-lg col m-2" name="date" default="" /> <input type="text" class="form-control-lg col m-2" name="location" placeholder="Where are You ?" /> </div> <div class="row m-2"> <input type="text" class="form-control col m-2" name="hashtags" placeholder="Hashtags" /> <input type="text" class="form-control col m-2" name="tags" placeholder="Tag Your Friends" /> </div> <div class="row m-4"> <input type="submit" class="btn btn-primary btn-lg col" id="abc" value="Create"> </div> Javascript File document.querySelector(".tui-image-editor-load-btn").setAttribute("name", "PostedImage") views.py def newpost_view(request,email,*args,**kwargs): if request.method == 'POST': newpost = { 'date':request.POST['date'], 'location':request.POST['location'], 'hashtags':[f['value'] for f in json.loads(request.POST['tags'])], 'tags':[f['value'] for f in json.loads(request.POST['hashtags'])] } print(newpost) print(request.FILES.get('PostedImage')) id = email[0:5] variables={'id':id} return render(request,'newpost.html',variables) I want to get the Image from the input. the element itself is added via javascript, because I am using a Vanilla image manipulation snippet It gets rendered fine and my browser shows the element with the name tag added as "PostedImage" . But it shows up as an error as request.FILE['PostedImage'] shows up empty. Is it that i can't add elements once the page is loaded or I can't add name tags after and django is not reading them? I can't do this using … -
Deleting object in Django
What is the best practice to delete object in Django? Using simple "a tag" with the link to the view like this: def deleteStudent(request,id): student = get_object_or_404(Student, id = id) student.delete() return redirect('/') or using post method: <form method="POST"> {% csrf_token %} Are you want to delete this item ? <input type="submit" value="Yes" /> <a href="/">Cancel </a> </form> and in views: def deleteStudent(request, id): student = get_object_or_404(Student, id = id) if request.method =="POST": student.delete() return redirect('/') return render(request, "delete_view.html") I saw in courses that people use both of the methods (it's example code, I'didn't test it or secure views). So if we can delete objects with "POST" method, can I say in the job interview that "POST method can be also used to delete objects"? Thanks for all answers. -
UI video play Issue but works perfectly on Postman
I am not able to play video on UI received from the django backend. I am using normal javascript on UI and Django on the backend. Please find the backend code snippet: file = FileWrapper(open(path, 'rb')) response = HttpResponse(file, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=my_video.mp4' return response The video plays perfectly on Postman but cant play on the UI screen. The UI code is below: function getUploadedImageAndVideo(combined_item_id){ request = {} request["combined_item_id"] = combined_item_id; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { vdata = this.responseText; var src1 = document.getElementById('src1'); src1.setAttribute("src", "data:video/mp4;base64,"+vdata); //myVid.setAttribute("src", vdata); //doesnt work either var src2 = document.getElementById('src2'); src2.setAttribute("src", "data:video/mp4;base64,"+vdata); //myVid.setAttribute("src", vdata); //doesnt work either return } } xhttp.open("POST", port + host + "/inventory_apis/getUploadedImageAndVideo", true); xhttp.setRequestHeader("Accept", "video/mp4"); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.setRequestHeader("X-CSRFToken", getToken()); xhttp.send( JSON.stringify(request) ); } on html side: <video controls=""> <source type="video/webm" src="" id="src1"> <source type="video/mp4" src="" id="src2"> </video> Network Response of function call: "ftypmp42 ... isommp42 ... mdat ... ó! ... °}b ... $¥Ð" I am not able to play video on the UI Side. Please Help. -
Django web frame work client server chat communication project
So basically this is a client server communication application which is been written in python and been successfully executed.For the same code i need to built a client separate and a server separately. My client Server program communicate on an self written algorithm which is included separately in the code already.. So i just need a help on how to add client and server separately in a project or should i create a separate project for client and server. Please help me out . I have tried different some method but that do not work. Thank you for advance for the help -
Django Microsoft Graph Authentication
I'd like users to be able to login to my Django app using their Microsoft personal, work or school account. I have no interest in any profile or other data from the user's account. I just want authentication. I've been playing with django-allauth and and Azure portal and have successfully set things up so I can log in with my personal outlook.com account. I've set the AD tenants up to allow for personal and institutional accounts. I've successfully served the .wellknown json and was able to verify the app in Azure. I run into trouble when I try to log in with a Microsoft 365 work or school account. The consent form shows the app as "unverified" and indicates that the app wants profile information and to store data. I ended up in a rabbit hole of Microsoft AD documentation about MPN IDs and such. Before I go further I want to know if I what I want to do is even possible. Keeping in mind that I'm not interested in profile information, can I achieve authentication in Django with a users Microsoft Work or School account? If so, what do I have to do? -
Django : Define url with the pk value in the middle and add it to the template
After the login, the user is redirected to a page where he has to select a contract value. The value selected redirects him to the specific home page. It is the home page concerning the contract where there are several apps. The structure of the URLS is : urlpatterns = [ path('selectcontrat', views.selectcontrat, name='selectcontrat'), path('home/<int:id_contrat>/', views.home, name="home"), path('home/<int:id_contrat>/upload', views.upload, name="upload"), ] The views : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) @authenticated_user @check_user_rights() def home(request, id_contrat=None): context = initialize_context(request) context["id_contrat"] = id_contrat return render(request, 'home.html', context) @authenticated_user def upload(request, id_contrat=None): bla_bla_bla return render(request, 'base/upload.html', context) How do I add the urls/links in the template for the app "Upload Files" with the id_contrat value in the middle ? This is not working : <li><a href="{% url 'upload' %}">Upload Files</a></li> -
Django get results from multiple tables based on date range
Like said in the title. I have multiple tables in Postgres, where each of them have date range column. I want to pass a date range query to Django and get results from all of those different tables together ordered by date. What is the best and most efficient approach to this issue ? -
Python/Django - How to pass value from html to view via {% url %}?
I have a Django application that contains a form where the user can select "choice1" or "choice2" . So what I'm trying to do is that when an user gives an input via the radiobutton in the html and clicks "Update", it sends the new values (view.choice1 and view.valuechoice2 which are Boolean values) of to my a view, and prints the new values in my console. What I have is the following: choiceMenu.html <form class="card" action="" method="POST" enctype="multipart/form-data"> <input type="radio" name="update_choice" value="choice1"> Choice1 </input> <input type="radio" name="update_choice" value="choice2"> Choice2 </input> <div class="form-group"> <a href="{% url 'core:choicemenu:choices' view.choice1 %}" class="btn btn-secondary btn-sm">Update</a> </div> </form> model.py class ChoiceModel(models.Model): choice1 = models.BooleanField(default=False) choice2 = models.BooleanField(default=True) views.py class ChoiceMenu(generic.TemplateView): template_name = 'core/choiceMenu.html' context_object_name = 'choicemenu' current_model_set = ChoiceModel.objects.get(id=1) choice1 = int(current_model_set.choice1 == True) choice2 = int(current_model_set.choice2 == True) class ChoiceSetting(generic.TemplateView): extra_context = {"choices_page": "active"} context_object_name = 'choices' template_name = 'core/choices/choiceindex.html' def get(self, queryset=None, **kwargs): choice1 = self.kwargs.get("choice1") logger.info(choice1) ### <<-- I want to get this printed in my console return redirect(reverse("core:choicemenu")) urls.py app_name = 'core' urlpatterns = [ path('choicemenu', login_required(views.ChoiceMenu.as_view()), name='choicemenu'), path('choicemenu/choices/<int:choice1>/', login_required(views.ChoiceSetting.as_view()), name='choices') ] So, what I want is that when the user selects choice1 and pushes the button Update, it prints 1 … -
Cross-Origin-Opener-Policy header error when making GET request in Django
I'm making a stock app which displays live market data via Alpaca API. The error is The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. Here's how I'm making the request: symbol = 'AAPL' url = f'https://data.alpaca.markets/v2/stocks/{symbol}/trades/latest' requests.get(url, headers={ 'APCA-API-KEY-ID': API-KEY-ID, 'APCA-API-SECRET-KEY': API-SECRET-KEY, }) My request works when market is closed, but not open. However, if I run the code in a console during open hours, it still works so the API endpoint should be correct. In Django settings, I have: ALLOWED_HOSTS = ['market-master.herokuapp.com'] CSRF_TRUSTED_ORIGINS = ['https://market-master.herokuapp.com'] My site is https, is there an additional header I'm missing? I'm not sure how to "deliver the response using HTTPS protocol". -
Fail to Add Google pay into a django project
I want to add payment subscription in my Django project using Google pay but I don't know how to made that happen. I want a user to pay $5 dollars a months in my website. The stripe is not working in my country. I don't want to use PayPal also, I just want to use Google pay or any other payment processing in to Django website. Is any body who can help me do that please. I'm beginner in payment processing. -
How to get a list of all custom Django commands in a project?
I want to find a custom command in a project with many apps, how to get a list of all commands from all apps? -
Can I convert my Django app in an IOS app?
I'm currently creating a Django app, and I need to turn it into an IOS app. However, after looking online, I'm seeing conflicting statements on if it's possible to do so or not. Is it possible to convert my Django app (both front and backend) into an IOS app, or can it only be done for the backend? -
IntegrityError at /accounts/signup/ NOT NULL constraint failed: users_user.birth_date in Django allauth form
I get the following error when I try to signup using Django allauth form with custom user model. IntegrityError at /accounts/signup/ NOT NULL constraint failed: users_user.birth_date This is the custom user model and its manager I use: from django.contrib.auth.models import AbstractUser, BaseUserManager ## A new class is imported. ## from django.db import models from datetime import datetime class UserManager(BaseUserManager): """Model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Make and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Make and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Make and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) # User model class User(AbstractUser): """User model.""" username = None email = models.EmailField(verbose_name='email address', unique=True) first_name = models.CharField(max_length=128, blank=False) last_name = models.CharField(max_length=128, blank=False) … -
Form Create View and 3 hierarchical models - Limit Choices for ForeignKey
I am trying to create an 'Expense Tracker'. I have query regarding create view and Models with 3 hierarchical levels. For eg:- class ExpenseYear(models.Model): year = models.PositiveIntegerField() class ExpenseMonth(models.Model): month = models.CharField(max_length = 14,blank = False) month_year = models.ForeignKey(ExpenseYear,related_name = 'month',on_delete=models.CASCADE) class Expenses(models.Model): expense = models.PositiveIntegerField() expense_month = models.ForeignKey(ExpenseMonth,related_name = 'expense', on_delete=models.CASCADE) Now, while creating CreateView for 'Expenses' model, i am facing an issue. I want to display only the months in that particular year (in 'expense_month' foreignkey), but all months of all the years are being displayed in the 'expense_month' foreignkey. This is what i am getting - CreateView I searched stackoverflow about limiting foreignkey choices and ended up finally with another code, but now no months are displayed in the foreign key Forms.py #forms.py class ExpensesForm(forms.ModelForm): class Meta(): model = Expenses fields = ('expenses','expense_month') def __init__(self, *args, **kwargs): month_year_id = kwargs.pop('month_year_id') super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['expense_month'].queryset = ExpenseMonth.objects.filter(month_year_id=month_year_id) Views.py #views.py class ExpensesCreateView(CreateView): model = models.Expenses form_class = ExpensesForm def get_form_kwargs(self): kwargs = super(ExpensesCreateView, self).get_form_kwargs() kwargs.update({'month_year_id': self.kwargs.get('month_year_id')}) return kwargs However, as i said no months are displayed if i write this code. This is what i am getting if i write the above code - CreateView How to limit foreignkey …