Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: categories.map is not a function in ReactJs
How to fix TypeError: categories.map is not a function ''' This is App.js: export default function Header() { const [categories, setCategories] = useState([]); useEffect(() => { const loadCategories = async () => { let res = await API.get(endpoints['categories']) setCategories(res.data) } loadCategories() }, []); return ( <Navbar bg="light" expand="lg"> <Container> <Navbar.Brand href="#home">ECoursesAPP</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <Link className="nav-link" to="/">Trang chủ</Link> {categories.map(c => <Link className="nav-link" to="#link">{c.name}</Link>)} </Nav> </Navbar.Collapse> </Container> </Navbar> ) } ''' This is API.js: ''' import axios from "axios"; export let endpoints = { "categories": "/categories/" } export default axios.create({ baseURL: "http://localhost:8000" }) ''' -
backend design to connect to android app and web ui
I am writing a python web application in Django to save day to day personal expenses on a SQL database. I want to connect my backend both from web UI and from android app. I know I can use any web front end tech like angular JS etc. for Web UI. My question is how to write Android app for this ? Which front end tech should be used? How to connect this to my backend? Where to deploy my backend code ? --- web UI (react) sql -- web backend (running on cloud) --- --- android app (????) Thanks -
How do I access the data from inside a nested for loop
I want to do something like below in html where multiple "spots" are displayed, and within each spot the "links" associated to each specific spot is displayed. How would I write the logic to display the specific links for each spot? html {% for spot in spots %} <div> <h2>{{ spot.title }}</h2> </div> {% for link in links %} <div> <h3>{{ link.url }}</h3> </div> {% endfor %} {% endfor %} My models are as below. SpotLinks is the intermediate table for Links and Spots table. models.py class Spots(models.Model): title = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) class Links(models.Model): title = models.CharField(unique=True, max_length=155, blank=True) url = models.CharField(max_length=75, blank=True) class SpotLinks(models.Model): link = models.ForeignKey('Links', models.DO_NOTHING) spot = models.ForeignKey('Spots', models.DO_NOTHING) I tried links = Links.objects.filter(spotlinks__spot=spots) in views.py but because spots has multiple spots in it it doesn't get filtered. Will the logic be written in the views.py or as django templates in the html file? Im new to web development so any direction would help. Thanks! views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() links = Links.objects.filter(spotlinks__spot=spots) context = { 'spots': spots, 'article': article, 'links': links} return render(request, 'articletemplate.html', context) -
Import "ckeditor.fields" could not be resolved
I am trying to install ckeditor in my django forms. I seem to have no problem with the pip install django-ckeditor however once it is installed and I have added it to my settings, I can not import RichTextEditor in my models.py file. The error that comes up is 'Import "ckeditor.fields" could not be resolved'. Here is the code: settings.py: INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', ] models.py: from django.db import models import uuid from ckeditor.fields import RichTextField -
about open csv file and read line by line in and choice randomly python
I have a csv file that contains questions, options and answers. I want to open that file in a class called quiz to show the question and answer randomly and the user enters the answer And compare the answers -
How to name an object in Django by using user input? [duplicate]
Here I am on the admin site adding the topics I want to learn about. I want the object to be the topics I add to the site. Is there a way to do this? I am not sure if I would do this in the models.py file or in the admin.py file. Here is my models.py file Is there away that I can tell django to take the user input and use that input instead of the word "object"? When I click on the object I can see the name that I inputted. I wish I could use that name and replace the object that is currently being returned. -
Django Rest API returns 403 error only on iOS when using react native
I have a app which uses React Native as frontend and django as backend. When I try to fetch data from the API, it works perfectly fine on android but on iOS it returns a error 403 forbidden. In the django views, I have put the following inside every views: permission_classes = [permissions.IsAuthenticated] When fetching the API, I have put the following: const userToken = await AsyncStorage.getItem('userToken'); const headers = {"Authorization": `Token ${userToken}`} There are some views that can run on iOS. I notice that for those which cannot be run on iOS are those that I have customize the method in the views (say, I have override the get method in the view). -
Add object to database without calling save
I would like to know if it is possible to add an object to the database without calling save(). foo = Foo.objects.create( #fields ) lst_bars = [] for bar in MyModel.objects.filter( #fields ): lst_bars.append(Bar( foo_id=foo.id, # fields )) Bar.objects.bulk_create(lst_bars) foo.save() In this code I'm creating Foo, then using its id as a reference when creating Bar. After bulk creating all Bar objects, I call the foo save. In the foo save() I call each bar save(), then aggregate all bars data and fill the Foo fields. In total the method save is being called two times, but in the create() I would like to just create without saving, that way it wouldn't make calculations when there is no data. -
django-excel pyexcel show unknown parameters for django heroku
My django app deployed in heroku managed to show upload file form. However once I try uploading Excel xlsx file, it shows UnknownParameters at / Please check if there were typos in function parameters: {'model': None, 'initializer': None, 'mapdict': None}. Otherwise unrecognized parameters were given. Following installation setup has done for django-excel requirements.txt pyinstaller django-excel pyexcel-xls pyexcel-xlsx pyexcel-ods I am sure that my models.py is connected and along with the mapdict parameters matches correctly I've seen similar issue Why pyexcel throws exception "UnknownParameters: Please check if there were typos in function parameters"? and I tried installing pyinstaller along with hidden imports --hidden-import pyexcel_xls --hidden-import pyexcel_xls.xlsr --hidden-import pyexcel_xls.xlsw but unfortunately it still doesn't work for my app I wonder if there is any clue to solve this for me to run my django web application on heroku? or any advice or learning for hidden-import to run within heroku web app? -
TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list (Django)
I am trying to add a profile photo to the client through the 'Customer' model in the administration panel. models.py from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name settings.py STATIC_URL = '/static/' MEDIA_URL = '/imagenes/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_ROOT = [BASE_DIR/'static/images'] I think I have an error in setting static file paths; the truth is that I understand very little the way in which I should configure it and I do not understand why the error occurred .. Please, someone who can help me -
How can I add additional field in DRF model instance creation
I have a classroom model in django DRF that looks like this: class Classroom(models.Model): class PublishedClassrooms(models.Manager): def get_queryset(self): return super().get_queryset().filter(status="published") options = (("published", "Published"), ("draft", "Draft")) name = models.CharField(max_length=255) code = models.CharField(unique=True, max_length=8) subject = models.CharField(max_length=255, null=True, blank=True) section = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) status = models.CharField(max_length=10, choices=options, default="draft") owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) dateCreated = models.DateTimeField(default=timezone.now) dateUpdated = models.DateTimeField(default=timezone.now) objects = models.Manager() # default manager publishedClassrooms = PublishedClassrooms() # custom manager class Meta: ordering = ("-dateUpdated",) def __str__(self): return self.name what I want is to generate unique code field in the serializer upon creation of an instance using this code: def get_code(): codeID = shortuuid.ShortUUID().random(length=8) return codeID Can anybody guide me on this? -
Django courier logistics service shipment tracker
How can I enable a live track in Django. Like, I wanna know how to implement a shipment tracking system or model in Django, whether live track or by code number, I'm building a courier logistics service website -
Range Filter between two fields
i have TaskAdmin with list_filter: from rangefilter.filters import AdminSplitDateTime, DateTimeRangeFilter as OriginalDateTimeRangeFilter ('created_at', OriginalDateTimeRangeFilter), ('finished_at', OriginalDateTimeRangeFilter), I receive next URL: /admin/core/task/?&created_at__range__gte_0=2021-10-01&created_at__range__gte_1=10%3A50&created_at__range__lte_0=2021-10-08&created_at__range__lte_1=22%3A50 And same for finished_at: /admin/core/task/?&finished_at__range__gte_0=2021-10-01&finished_at__range__gte_1=10%3A50&finished_at__range__lte_0=2021-10-08&finished_at__range__lte_1=22%3A50 It works only with created_at and finished_at dates if they are separate, but I need to connect them, i need make one filter between created_at and finished_at dates. That is, so that the DateStart is compared with created_at, and the DateFinish is compared with finished_at. So i need receive next URL request: /admin/core/task/?&created_at__range__gte_0=2021-10-01&created_at__range__gte_1=10%3A50&finished_at__range__lte_0=2021-10-08&finished_at__range__lte_1=22%3A50 Try to do this, but not worked for me ('created_at', 'finished_at', OriginalDateTimeRangeFilter), How i can do it, maybe some of you have faced the same problem? I hope I was able to explain what I need Thanks -
How do I fix this issue with if statement being ignored in views.py?
Why is the if statement in twilio_view2 being ignored? When this is executed it just skips down to the else statement. See the TwiML response. Thanks in advance to anyone who helps. views.py from example import test1_is_valid, test2_is_valid def twilio_view2(request: HttpRequest) -> HttpResponse: digits = request.POST.get('Digits') response = VoiceResponse() if test1_is_valid(digits) and test2_is_valid(digits): gather = Gather(input='dtmf', action='/twilio_view3', method='POST') gather.say('Blah blah blah.') response.append(gather) else: response.say('Something other than Blah blah blah.') response.redirect("/twilio_view1") return HttpResponse(str(response), content_type='text/xml') TwiML response <Response> <Say>Something other than Blah blah blah.</Say> <Redirect>/twilio_view1</Redirect> </Response> -
DJango Template - Render a field from a form using a string
According to django's docs: We don’t have to let Django unpack the form’s fields; we can do it manually if we like (allowing us to reorder the fields, for example). Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. Great! I want to make it more complicated... I want to do something to the effect of {{ form."somefield" }} so that way I can essentially do: {% for i in '012345'|make_list %} {% with y=forloop.counter|stringformat:"s" %} {% with somefield="somefield"|add:y %} {{form.somefield}} #either this {{form.somefield|add:y}} #this {{form.somefield{{i}}}} #this {{form.somefield{{forloop.counter}}}} #this #or other variations of that {% endwith %} {% endwith %} {% endfor %} Basically I need to add some variable to the end of the "somefield" attribute to be able to referrence a field that has a number at the end of it. Thank you!!! -
None typeobject in success_url django
I have a user registration form as shown by the code below. views.py class UserCreateView(CreateView): form_class = UserCreateForm model = User template_name = 'internethq/user_form.html' success_url = '/internethq/login' forms.py class UserCreateForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password1', 'password2' ] def clean_password1(self): exp = re.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$") if exp.match(self.cleaned_data['password1']): return self.cleaned_data['password1'] else: raise ValidationError('Must contain one uppercase letter, one lowercase letter, one number and one special character.') def save(self, commit = True): user = super().save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() The Error Internal Server Error: /internethq/signup/ AttributeError at /internethq/signup/ 'NoneType' object has no attribute '__dict__' Traceback (most recent call last): bit of trimming here... File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/python3.6/site-packages/django/views/generic/edit.py", line 113, in get_success_url url = self.success_url.format(**self.object.__dict__) I thought success_url looked correct but is there an error I'm missing? This codes runs fine in the development server. Thanks for your help. -
"List index out of range" for Django Steam API
I'm working on an app in Django that lets you see stuff about a steam user, when typing in their steam ID. I'm using the Django Steam API found at this link: https://pypi.org/project/django-steam-api/ which, unfortunately, doesn't provide some documentation / enough help on how to properly set it up. I followed the steps from there. Installed the pip package, added django-steam-api to the INSTALLED_APPS tuple, generated a STEAM_API_KEY from their official site (on "localhost", because my web app isn't hosted at this moment) and also updated the database by applying the current migrations. I'm having a view in backend/views.py, (backend being my app name created with the django-admin startapp backend command), that takes data from a form that contains a textbox called steam_user_id using the POST method. I'm trying to get everything from Steam about the user with the id steam_user_id, but when I call, inside the view, the method: Player.objects.steam_create(steam_user_id) (...) I receive the following error on my page: IndexError at {{ /link_to_my_view/ - replaced it manually here to avoid complications }} list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/profile/edit/ Django Version: 3.2.7 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\matea\AppData\Local\Programs\Python\Python39\lib\site-packages\django_steam_api\managers.py, … -
Django DRF Behave - How to load test fixture data into test database before testing
The documentation only mentions fixtures as part of browser setUp and tearDown. What about data? How does one load and destroy test data such as test-users.json into test database for behave tests? I understand one usually loads the test fixtures inside a testing class such as: class FooTest(LiveServerTestCase): fixtures = ['test-users.json'] I have already have my FIXTURE_DIRS set in settings file, and fixtures ready, but don't know how to implement into the behave tests. Could anyone please help, thanks in advance. Djangov3.2.7 DRFv3.12.4 Behavev1.2.6 Note that I am only using Behave and not Behave-Django -
Renaming uploaded files with django primary keys
Using the accepted and second answers in this post, I've created a rename file function which is in my models.py: class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] # set filename as random string if instance.pk: filename = '{}/{}'.format(instance.pk, filename) else: filename = '{}/{}.{}'.format(instance.pk, uuid4().hex, ext) # return the whole path to the file return os.path.join(self.path, filename) path_and_rename = PathAndRename("") class Post(models.Model): File = models.FileField(blank=True, null=True, upload_to = path_and_rename) So the way it's supposed to work is that it outputs to media/<object.pk>/<filename> if a primary key is found, otherwise it outputs to media/None/<hex-generated-filename> If I use my post create view to upload the file, there is no PK assigned to the record yet, so it defaults to media/None/<hex-generated-filename>. If I then edit the post with my post update view, the file gets correctly output to media/<object.pk>/<filename> So essentially the issue is that the file gets uploaded before the PK is assigned. Does anyone know how to fix it? Here are my relevant views: class PostCreateView(LoginRequiredMixin, FormView): template_name = 'trucking/post_form.html' form_class = RecordForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.author = User.objects.get(username=self.request.user) … -
CSRF verification failed. Request aborted - even after adding {% csrf_token %}
I am getting the CSRF verification failed. Request aborted error. I did extensive research and everything pointed out to adding {% csrf_token %} into the template tag with the POST form and I did that but still getting the same error. -
JavaScript submit not working Django From
I have a simple form that uses JavaScript to validate and submit the form using POST to the database. The script works for 2 forms but won't submit for other forms for some reason and I can't work out why. I've even copied the existing form and JS replaced it with new names and it still doesn't work and I cannot figure out why. I've tried to debug, but I'm getting http200 for every request so not throwing any errors that I can see. Working version: var investor_form = document.getElementById("add-investor"); investor_form.addEventListener("submit", function (e) { e.preventDefault(); if (validated(this)) { this.classList.add("was-validated"); var i_name = document.getElementById("investor-name").value; var i_website = document.getElementById("investor-website").value; var i_portfolio = document.getElementById("investor-portfolio").value; var i_comment = document.getElementById("ckeditor-classic").value; const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value; const formdata = new FormData(); formdata.append("investor_name", i_name); formdata.append("investor_website", i_website); formdata.append("investor_portfolio", i_portfolio); formdata.append("investor_comment", i_comment); const xhr = new XMLHttpRequest(); xhr.open("POST", "/apps/add_investor"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(formdata); xhr.onload = () => { window.location.reload(); }; } }) // Form validation function validated(form) { console.log(form) var i_name = document.getElementById("investor-name"); var i_website = document.getElementById("investor-website"); var i_portfolio = document.getElementById("investor-portfolio"); i_name_value = i_name.value.trim(); i_website_value = i_website.value.trim(); i_portfolio_value = i_portfolio.value.trim(); if (i_name_value === "") { message = "Please fill investor name field" setErrorFor(i_name, message); } else { setSuccessFor(i_name) } if (i_website_value … -
How to remove Image location showing in body although it is in a Meta Tag
I have a Django project and I added an Image meta tag as following in the base.html <meta property="og:image" content="{% block image %}{% endblock %}"> <meta property="og:image:type" content="image/jpeg"> <meta property="og:image:width" content="300"> <meta property="og:image:height" content="300"> in the home.html page I have added the following: {% extends 'base/base.html' %} {% load static %} {% block content %} {% block description %}{{ info.description }}{% endblock %} {% block image %}{{ info.avatar.url }}{% endblock %} My issue is that in the home page in the top the location of the image is showing as per below: I am not sure why the image link is showing and I am not sure how to remove it. My question is how to remove the location of the file from the page. -
Getting An Template Rendering Error When Using Django SocialAuth App
I installed django-socailauth app in my Django project and followed the below tutorial of setting it in the python project. https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html But when running the Django server the site starts normally and the issue comes when I click the login button in my application. It gives me the below Template Rednering Error Reverse for 'begin' with arguments '('facebook',)' not found. 1 pattern(s) tried: ['social-auth/$login\/(?P[^/]+)\/$'] -
Django - Unit test an object has been deleted - how to use assertRaise / DoesNotExist exception
I would lioke some help to unit test a function that deletes an object in a Django app The problem I display a list of values, it includes a bin icon to delete one value, and my view seems to work fine (at least according to the test I made). How can I unit test it? I'm not able to find out the right way to do yet. I searched the web and found the DoesNotExist exception, but I'm afraid I'm not able to use it, as I got a matching query does not exist error. Could you please advise me on how to proceed? What I tried Here is my current whole code for the test: class TestAdmUsers(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.usr11 = create_dummy_user(self.company, "user11") self.usr13 = create_dummy_user(self.company, "user13") self.usr14 = create_dummy_user(self.company, "user14") self.client.force_login(self.user_staff.user) def test_delete_user(self): test_usercomp_id = self.usr13.id url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id]) response = self.client.get(url, follow=True) self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id)) The test log is the following: Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_delete_user (polls.tests_admin.TestAdmUsers) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id)) File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\manager.py", line 82, in … -
Use phone number for authenticate user in Django
My custom user uses the mobile number as username If a user registers with a phone number, but if he does not confirm it, it stays in the database and can no longer be used. Do you have a solution for this problem? views.py def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.phone_number = registerForm.cleaned_data["phone_number"] user.set_password(registerForm.cleaned_data["password"]) user.is_active = False user.save() otp_user = f"{user.otp}" print(code_user) send_sms(otp_user, user.phone_number) return render(request, "account/verificationpage.html", {"form": registerForm}) else: return HttpResponse("Error handler content", status=400) else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}