Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static files are being served with HTTPS while the running server is HTTP
I'm using Amazon lightsail instance and introduced Certbot into my service on the Nginx-Gunicorn-Django stack in order to serve my site with SSL implemented. I took a snapshot of this server and created a new one which I want to serve without SSL but when the server turns on I can see the page but all images, css, js show ERR_CONNECTION_REFUSED. Which I found the issue comes from searching for these files in HTTPS when I want them to be served in HTTP. Here are some things I've tried Removed SSL Setting Nginx Completely removed Nginx serve and ran server on manage.py 8000 Disabled SSL related settings and DEBUG MODE = True Image shows up if I open url to http://img.jpg How can I solve this issue? JS ERROR IMG -
My detail page for my app isn't showing in the browser
There is my html template which works perfectly. No template errors. {% extends 'learning_logs/base.html' %} {% block title %}Topic {% endblock title %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} You will find below my view.py. In actual fact the application does not any error. def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ``class Entry (models.Model): topic = models.ForeignKey('Topic', on_delete = models.CASCADE, max_length = 200) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True)` -
Django form updates front end even if username already exists
Below is my Django form that allows users to update their username and email. If they enter a username or email that's already taken by another user, the form correctly displays an error message. However, the front end still updates with the username or email that they entered. How can I update the else block in views.py below to show the username/email that is actually stored in the database, not the one the user just entered? Screenshot: forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'lat', 'long', 'travel_radius', 'location_name'] widgets = {'lat': forms.HiddenInput(), 'long': forms.HiddenInput(), 'travel_radius': forms.HiddenInput(), 'location_name': forms.HiddenInput()} views.py @login_required def account(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid(): u_form.save() messages.success(request, f'Your account has been updated!') return redirect('account') else: #<- HOW CAN I SHOW THE ORIGINAL USERNAME, NOT THE USERNAME ENTERED? stored_user = User.objects.filter(id=request.user.id).first() u_form = UserUpdateForm(request.POST, instance=request.user) u_form.username = stored_user.username # Get the values on this user that are stored in the DB u_form.email = stored_user.email u_form.fields['username'].initial = stored_user.username return render(request, 'users/account.html', {'u_form': u_form} ) else: u_form = UserUpdateForm(instance=request.user) context = { 'u_form': u_form } return render(request, 'users/account.html', context) -
Django REST Fw - How to dynanically create fk relation when neither object exists initially?
[I'm asking about DRF but this question is more about a general approach to a situation like mine] Let's say on my backend I have a Category and a Question model like these: class Category(models.Model): name = models.TextField() class Question(models.Model): text = models.TextField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, related_name="questions" ) I have a vue frontend in which I have a form that allows me to create categories and questions. The way it's laid out is I have an add button for categories in the form, an add button for questions, and for each question I can select the category it belongs to. All questions and categories are keyed with a uuid in my vue.js frontend, but that's not the id they end up having on the db of course. When I POST my form to the DRF backend, neither the categories nor the questions exist yet, so I can't just send the questions like this: { text, categoryId }. A simple way to handle this could be to send the form like this: categories: [ { name: "cat1", questions: [ { text: "question1" }, // ... }, // ... ] However, the actual structure of my app is more … -
ValueError at /app/ when accessing model data
I am new with django, I've learnt by following the documentation, but it seems django doesn't want to retrieve any data from the model, on a new project. The issue is with the line : "latest_weapons = Weapon.objects.order_by('-id')[:5]". I tried other field names, other parameters, but still a value error... :( If someone has any idea, I would greatly appreciate! >//< app/views.py : from .models import Weapon # OK ! def detail(request, weapon_id): return HttpResponse("Analyzing weapon n°%s" % weapon_id) # No way ! def index(request): latest_weapons = Weapon.objects.order_by('-id')[:5] # Crash (maybe because it returns None?) template = loader.get_template('armory/index.html') context = { 'latest_weapons': latest_weapons, } return HttpResponse(template.render(context, request)) app/models.py : # The Model class Weapon(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Identifier id_item = models.ForeignKey('Item', models.CASCADE, db_column='ID_Item') # Global ID of this weapon in the items table. lvl = models.PositiveIntegerField(db_column='LVL') # Level of the weapon. name = models.CharField(db_column='Name', max_length=32) # Label of the weapon (rewrites item name). attack = models.IntegerField(db_column='ATK') # Attack of the weapon. crit = models.IntegerField(db_column='CTR') # Critical Hit of the weapon. weapon_type = models.ForeignKey('WeaponType', models.CASCADE, db_column='Type') # ID of the weapon type. class Meta: managed = False db_table = 'Weapons' def __str__(self): return self.name # Only returning the name … -
how to keep track of user opened profile like linkedin in django and flutter and to give notification too like that?
I want to keep track of the user, who has opened whose profile and how to give notifications too as in linkedin . I am going to implement it using Django as back-end and Flutter as Front-end. -
django.db.utils.OperationalError: (1044, "Access denied for user to database) when having permissions
I'm trying to connect my django project to its MySQL db in an Amazon EC2 instance, but I keep getting the error in the title. What's weird is that I granted all the privileges to the user, but I still keep getting the error: django.db.utils.OperationalError: (1044, "Access denied for user 'chile_analyst'@'%' to database 'lms_chile_integration_local'") I triple-checked the usernames and passwords coming from the environment file and they are OK. I also checked the grants for the user: mysql> SHOW GRANTS FOR 'chile_analyst'@'%'; +--------------------------------------------------------------------------------------------------+ | Grants for chile_analyst@% | +--------------------------------------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'chile_analyst'@'%' WITH GRANT OPTION | | GRANT ALL PRIVILEGES ON `lms_chile_integration_local`.* TO 'chile_analyst'@'%' WITH GRANT OPTION | +--------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec) I can connect to the databse using: mysql -u chile_analyst -p, but Django seems to be throwing this error when trying to migrate. What am I missing? -
Django 3 - ORM "AND" logic in filtering
I have a Query. qu = Product.objects .filter(color = 'black') .filter(color = 'white') .all() That gives me "And" logic which I'm looking for. Now I want to pass dict of criterions. my_crit = { 'color': 'black', 'color': 'white' } qu = Product.objects .filter(**my_crit) .all() That gives me OR, which is bad for me. So I tried Q. crit1 = Q(color='black') crit2 = Q(color='white') qu = hello = Product.objects .filter(crit1 & crit2) .all() This returns query with 0 results. So the question is - how can I use filter chain (AND logic) with dynamic inputs? (my own dict, etc). -
React/Django ; Error: Static/frontend/main.js not found
I am not sure why my static/frontend/main.js is not found when I clearly have it: Before running the server, I ran the dev script for webpack successfully, and it looks like everything was compiled into my main.js. I setup an API app and a frontend app on the same django project, and I am just testing to try and render information from my api to my frontend, but am unable to because of the error listed above. My API is called events and my frontend is react_frontend. I have listed below my App.js, my index.html, my views.py, my urls for both backend and frontend. App.js import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("events/api") .then(response => { return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( <div> {this.state.data.map(Events => { return ( <div> Event: {Events.title} Details {Events.details} </div> ); })} </div> ); } } export default App; const container = document.getElementById("api"); render(<App />, container); Index.html {% load static %} <!DOCTYPE html> … -
Django - Edit Or Delete Selected Rows In A Table
I'm trying to select one or multiple items in my table to do some manipulations, such as deleting the selected rows all at once. I want to keep it simple and do everything in html. I'm struggling to pass the status of each checkbox through my POST request. In my views, this is what request.POST returns: <QueryDict: {'csrfmiddlewaretoken': ['mtoFZt1PvlnAsYgEjT...'], 'selection': ['on', 'on', ...]}> How can I access the ID and value of each checkbox in the POST request? Am I missing something in my template? Template <form method="post" action="/products/delete"> <input type="submit" value="Delete"> {% csrf_token %} <table> <tr> <th></th> <th>Order #</th> <th>Product</th> <th>Price</th> </tr> {% for product in product_list %} <tr> <td><input type="checkbox" id={{product.id}} name="selection"></td> <td>{{product.id}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> </tr> {% endfor %} </table> </form> -
TypeError: unsupported operand type(s) for += 'set' and 'list'
File "C:\Users\sungk\Git\django_website\my_site_prj\urls.py", line 31, in urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) TypeError: unsupported operand type(s) for += 'set' and 'list' How to slove this problem... please~ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Change URL Path for View Profile Page - Django
How would one go about creating a user-profile page that other users can view without being able to edit the profile unless they are the user? The thing I'm trying to work out is how the url routing would work, is it best practice to store a user's profile on a profile/ or <user_id> page and then load in the individual user's data like recent posts using the username or id passed through the url? Also would this be handled by the one view and template and just use {% if request.user == profile.user %} to display things like edit profile etc? my problem is any user can edit for others there profiles when he edit url for example my id is www.test.com/profile/44/ and other user have this id www.test.com/profile/40/ okay ,, now when i edit the link to be 40 not 44 i can access and edit the second user ! how to fix that models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() def __str__(self): return self.user urls.py : from django.urls import path from blog_app.views import ProfileView urlpatterns = [ path('profile/<int:pk>/', ProfileView.as_view(), name='profile'), ] forms.py … -
django stripe create charge
When i call this method. charge = stripe.Charge.create( amount=request.POST.get('amount', ''), currency=request.POST.get('currency', ''), source=request.POST.get('source', ''), idempotency_key=request.POST.get('idempotency_key', ''), # https://stripe.com/docs/api/idempotent_requests description=request.POST.get('description', ''), statement_descriptor=request.POST.get('statement_descriptor', ''), ) It create success a payment what i checked in dashboard. I am using test API, i see anyone can create payment without submitting their card number. why? is it secure? Can you please tell me what does these success means? how can i charge by card and it should show success in stripe dashboard? any ideas? -
Using Django admin application AND disabling session middleware?
I am building a django server for an API that relies on JWT (or Token based - https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication) authentication for our users. I don't need session based authentication for any purpose. It creates an unnecessary query on each request, and also authenticates users when I don't want to authenticate them (I want browsers to only authenticate when it includes an Authentication header in the request, and stay AnnonymousUser otherwise. This is because it creates issues in some of my middlewares where I verify if I am dealing with a guest or a authenticated user). However, the issue comes when I try to use the admin application as well (I can't imagine building this app without the use of the django admin page). When I remove the session-related middlewares:(django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware) from my settings file, I get the following error when I do a runserver: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. Can someone think of a workaround where I can disable sessions in … -
React/Django: Database works, but React Is not Rendering the Views
I am trying to send information from my API and render it via React, but I get a blank screen. I am newer to fullstack development, so I am not sure where the disconnect. I can view dataentries I've created in the api, but cannot render these. I tried rendering the data is my models.py with my App.js App.js import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("events/api") .then(response => { return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( <div> {this.state.data.map(events => { return ( <div> Event: {events.title} Details {events.details} </div> ); })} </div> ); } } export default App; const container = document.getElementById("api"); render(<App />, container); models.py from django.db import models # Create your models here. class Events(models.Model): title = models.CharField(max_length=100) details = models.CharField(max_length=100) Please let me know if you need anything else. -
Django - Translation
I have this function that receives a location and returns a location code for it. def match_locations(location): if _('Everywhere') in location: location_code = 'loc_1' return location_code which gets called from this request: def return_more_jobs(request): url_parameter = request.GET.get("q") if url_parameter is not None: url_parameters = url_parameter.split('-') where = match_locations(url_parameters[1]) ... return HttpResponse(json.dumps(res), content_type="application/json") When I try to get the location code of the translation of 'Everywhere' it doesn't match. I have set the translation for 'Everywhere' in the .po file, but it doesn't work in this case. Thank you for any suggestions -
Page not found (404) Request Method: GET Request URL: http://localhost:8000/%23 Raised by:challengeide.views.send_challenge_request
This is challenge page When we go to ide page using the challenge button on the bottom and then click on submit button there then data is getting stored in database and function is running fine. But when I click on accept button and go to ide page and then click submit then data is not getting updated in database so basically function is not running and directly giving error 404 page not found. this is the error i am getting from django.conf.urls import url,include from django.urls import path,re_path from . import views app_name = 'challengeide' urlpatterns = [ path('challengeide/<int:sr_no>', views.show, name='show'), url('challengeide', views.qtn,name='test'), url('challenge/', views.challengeide, name='challengeide'), url('#', views.send_challenge_request, name='send_challenge_request'), ] this is my url.py <small class="float-right"> <div class="btn-group" style="display: inline-block;"> <form method="POST" action="{% url 'challengeide:show' r_request.qtn_id %}">{% csrf_token %} <button class="btn btn-success mr-2" type="submit" value="Accept">Accept</button> </form> </div> </small> this is my template for challenge page which has accept button <a class="btn btn-primary mr-2" href="{% url 'challengeide:send_challenge_request' %}" >Submit</a this is my template for challenge ide which has the submit button def send_challenge_request(request): user = get_object_or_404(User, id=to_id) print(user) score = ChallengeDemo.objects.filter(from_id=request.user,to_id=user,qtn_id=a) print(score) if(len(score)==0): print("dataintial") print(to_id) global data2 #user = data2 print(request.user) print(user) print("dataentry") entry = ChallengeDemo( from_id=request.user, to_id=user, score1 = … -
Serving static files from private s3 in django
Is there a way to serve static files from private s3. i know there are plenty of tutorials (like https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html) that help u in serving static files from public buckets. i serve my media files. and i get a signed url which will timeout after 120s. can i not get a similar url for static files? i am sorry if this sounds stupid. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DEFAULT_FILE_STORAGE ='storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = "***************" AWS_SECRET_ACCESS_KEY ="**********" AWS_STORAGE_BUCKET_NAME = "*********" AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_DEFAULT_ACL = None AWS_QUERYSTRING_EXPIRE = 120 AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my settings.py and my media files... i get a signed url when i query it.... but my static files ... i dont get a signed url (i.e. it looks like https://bucketname.s3.us-east-2.amazonaws.com/Path/file_fileext/) so i get a 403 forbidden note: my bucket iam user has AmazonS3FullAccess permission my bucket policy is EMPTY my block all public access is ON AND this is my cors policy [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ]``` -
showing error in map while fetching data in Reactjs after authentication in CRUD django REST api?
i am trying to do a CRUD app with backend in Django Rest Api and in frontend it would be react-hooks. The main functionality will be, after authentication it would show tasks created by the user and only user would see and edit, delete etc his own tasks. i have uploaded the API in heroku and Here is Api link and here is the openapi look. and you can find the source code in the github and here is the codesandbox for frontend FYI: i couldn't link the backend with the codesandbox frontend but in localhost frontend can communicate with the backend django part. i have used corsheaders to separate frontend and backend. i am practicing in this way just because the backend API would be reusable. i am not sure whether it is a professional practice or not. though i couldn't link my api with the codesandbox and it is for the show of my whole code. in dashboard.js, the below part is working: useEffect(() => { if (localStorage.getItem("token") === null) { window.location.replace("http://localhost:3000/login"); } else { fetch("http://127.0.0.1:8000/api/auth/user/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem('token')}`, }, }).then(res=>res.json()) .then(data=>{ setUserEmail(data.email); setLoading(false) setUsername(data.username) }) } }, []); Here the … -
Unable to POST Values And Create a Derived Value in Django
I am new to Django and still learning. Currently, I have a running code below which allows me to input data but I am unable to POST it to DB. I am not sure what I've done wrong. Model class ManHour(models.Model): station_choices = ( ('alpha','A'), ('beta', 'B'), ('gamma','G'), ) station = models.CharField( max_length=3, choices=station_choices, ) date = models.DateTimeField(auto_now=True) ops_1 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) ops_2 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) ops_3 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) Form from django import forms from webapp.models import ManHour class InputForm(forms.ModelForm): class Meta: model = ManHour fields = ['station', 'ops_1', 'ops_2', 'ops_3'] Views def form_page(request): if request.method == 'POST': properties_Form = InputForm(request.POST) if properties_Form.is_valid(): properties_Form.save() return redirect('home') context ={} context.update(csrf(request)) context['request'] = request context['form']= InputForm() return render(request, "form.html", context) HTML {% block content %} <form target="upload_frame" action="" method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form.as_p }}<br> <input type="submit" name="submit" value="Upload" id="submit"> </form> {% endblock %} Given the above code I am not sure why I am unable to post values to DB. My second question is that I want to create a derived field that sums ops1 and ops2 and I want it show to … -
How to customize the appearance of the Django change password form
How to customize the appearance of the Django change password form , i tried this but nothing happened i don't know why , any ideas ? forms.py : from django.contrib.auth.forms import PasswordChangeForm class MyPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["old_password"].widget = forms.PasswordInput(attrs={"class": "form-control"}) self.fields["new_password1"].widget = forms.PasswordInput(attrs={"class": "form-control"}) self.fields["new_password2"].widget = forms.PasswordInput(attrs={"class": "form-control"}) urls.py : # Change Password path( 'change-password/', auth_views.PasswordChangeView.as_view( template_name='user/commons/change-password.html', success_url = '/' ), name='change_password' ), views.py : from django.contrib.auth.views import PasswordChangeView from blog_app.forms import MyPasswordChangeForm class PasswordChangeView(PasswordChangeView): form_class = MyPasswordChangeForm template_name = "user/commons/change-password.html" change_password.html : <div class="form-group"> <form method="post"> {% csrf_token %} {{ form.as_p }} <a href="{% url 'home' %}">Back</a> <button type="submit">Submit</button> </form> </div> -
How to show only a few Many-to-many relations in DRF?
If for an example I have 2 models and a simple View: class Recipe(model.Model): created_at = model.DateField(auto_add_now=True) class RecipeBook(model.Model): recipes = model.ManyToManyField(Recipe) ... class RecipeBookList(ListAPIView): queryset = RecipeBook.objects.all() serializer_class = RecipeBookSerializer ... class RecipeBookSerializer(serializers.ModelSerializer): recipe = RecipeSerializer(many=True, read_ony=True) class Meta: model = RecipeBook fields = "__all__" What would be the best way, when showing all Restaurants with a simple GET method, to show only the first 5 recipes created and not all of them? -
Django Query how to sum returned objects method
I have a model: class TimeStamp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) t_in = models.DateTimeField(_("In"), auto_now=False, auto_now_add=False) t_out = models.DateTimeField( _("Out"), auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = _("TimeStamp") verbose_name_plural = _("TimeStamps") def __str__(self): return str(f'{self.t_in.date()} {self.user.get_full_name()}') def get_absolute_url(self): return reverse("TimeStamp_detail", kwargs={"pk": self.pk}) def get_total_hrs(self): if self.t_out: t_hrs = abs(self.t_out-self.t_in).total_seconds()/3600 else: t_hrs = '0' return str(t_hrs) then in my views.py def timeclock_view(request): week_start = timezone.now().date() week_start -= timedelta(days=(week_start.weekday()+1) % 7) week_end = week_start + timedelta(days=7) obj = request.user.timestamp_set.filter( t_in__gte=week_start, t_in__lt=week_end) obj.aggregate(total_hrs=Sum('get_total_hrs')) if obj: last = obj.last() context = {'obj': obj, 'last': last, 'week_start': week_start, 'week_end': week_end, 'week_total': total_hrs, } else: context = {} return render(request, 'timeclock/timeclock_view.html', context) how do i write this to get a sum of the hrs for the queryset? obj.aggregate(total_hrs=Sum('get_total_hrs)) is giving me an error django.core.exceptions.FieldError: Cannot resolve keyword 'get_total_hrs' into field. Choices are: description, id, note, note_set, pw, t_in, t_out, user, user_id -
How to solve MultipleObjectsReturned with ForeignKeywidget in django-import-export
I have a resource that should help me import data into my model but it doesn't work. I have tried all the options I could but to no success. This is the resource. class ImportStudentsResource(resources.ModelResource): klass = fields.Field(attribute = 'class',column_name='class',widget= ForeignKeyWidget(Klass,'name')) stream = fields.Field(attribute = 'stream',column_name='stream',widget=ForeignKeyWidget(Stream,'name')) gender = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name')) school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) class Meta: model = Students fields = ('school','adm','name','kcpe','klass','stream','gender','notes') import_id_fields = ('adm',) import_order = ('school','adm','name','kcpe','klass','stream','gender','notes') This is the data to import into the model through the resource This is the Traceback. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\Links_Online_Results\students\views.py", line 52, in post result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 741, in import_data return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 788, in import_data_inner raise row_result.errors[-1].error File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 658, in import_row self.import_obj(instance, row, dry_run) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 512, in … -
Django extra_context URL
I am trying to figure out how to pass in extra_context that takes a User instance's username and uses it for constructing the User's profile URL, whether it be using extra_context or other methods I have tried, such as get_context_data(). Note: I have included different attempts as one. views.py from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render from django.urls import reverse from allauth.utils import get_request_param from django.views import View from .models import CandidateProfile from .forms import CandidateProfileForm from allauth import app_settings from allauth.account.views import SignupView from allauth.account.utils import complete_signup, passthrough_next_redirect_url from allauth.exceptions import ImmediateHttpResponse class CandidateSignUpView(SignupView, View): def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def get_context_data(self, **kwargs): ret = super(SignupView, self).get_context_data(**kwargs) form = ret["form"] email = self.request.session.get("account_verified_email") if email: email_keys = ["email"] if app_settings.SIGNUP_EMAIL_ENTER_TWICE: email_keys.append("email2") for email_key in email_keys: form.fields[email_key].initial = email login_url = passthrough_next_redirect_url( self.request, reverse("account_login"), self.redirect_field_name ) redirect_field_name = self.redirect_field_name site = get_current_site(self.request) redirect_field_value = get_request_param(self.request, redirect_field_name) username = self.user.username ret.update( { "login_url": login_url, "redirect_field_name": redirect_field_name, "redirect_field_value": redirect_field_value, "site": site, "username": username, } ) return ret def form_valid(self, form): self.user = form.save(self.request, commit=False) self.user.is_candidate = True self.user.save() extra_context = {'username': self.user.username} success_url = f'profile/{self.user.username}/' try: return complete_signup( self.request, …