Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django freezer app - Checking a time delta
I am working on a project for organizing a freezer. Therefore I added a model called 'ShoppingItem'. It has an 'best before' date. Now I want to check three things via a function: Is the food expired? Is the food fine? Or is the food 'critical' (3 days before expiring) This is my whole models.py It includes the model itself and two functions. enter image description here enter image description here I tried on the expired function but can't come up with a solution -
PostgreSQL full text search giving different results for different database version
I am trying to use Postgres full text search with my Django project in order to search for products in my database. The shop_products table has a GIN index field search_vector. I also currently have two databases, with one being the production server that is hosted on AWS RDS (PostgreSQL 14.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 7.3.1 20180712 (Red Hat 7.3.1-12), 64-bit) and the other being my local development database (Version PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit). The issue I am having is that some search results work normally on the development server but not on the production server. For example, when I am looking for products with the word 'extreme' in them using the following query SELECT * FROM shop_products WHERE search_vector @@ websearch_to_tsquery('extreme'); Both of the databases have the exact same indexing where 'extreme' is stored as 'extrem' in the database, and searching for 'extrem' in both databases returns the same results. So is the reason for this the different PostgreSQL versions or is something else possible affecting the search results? -
connecting react native with django, fetching data
I just try to connect the native react app with the django backend. So in Django I installed the django.cors.headers. And i did the configuration in settings. I am using android studio. And I am using the emulator. And that works fine. And I have the settings for the cors in django: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:8081", "http://localhost:19006", "http://localhost:19002", "http://192.168.1.69:19000", ] and react native useEffect(() => { fetch("http://127.0.0.1:8000/animalGroups/group/", { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, }) .then((res) => res.json()) .then((jsonres) => setAnimalGroup(jsonres)) .catch((error) => console.error(error)); }, []); and this are the messages in react native: Opening on Android... › Opening exp://192.168.1.69:19000 on MY_ANDROID › Press ? │ show all commands › Reloading apps Android Bundling complete But I still get this errors: Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue So what I have to change? Thank you -
PyCharm Django test ModuleNotFoundError
Project tree: |___sb_website | |___article | | |__...py | |___home | | |__...py | |___sb_website | | |__dev_settings.py | | |__...py | |__manage.py | |__...py My django project development settings are dev_settings.py. I want to run my tests against these settings. When I use a Python configuration in PyCharm with these parameters test --settings=sb_website.dev_settings, script path ..\sb_website\manage.py I get the following Error: ERROR: sb_website.article (unittest.loader._FailedTest) ImportError: Failed to import test module: sb_website.article. Same for sb_website.home and sb_website.sb_website If use a Django Test configuration in PyCharm modules are imported and tests run fine. I'd like to learn the root cause of my problem as it is not the first time I faced this. What I tried: changed all imports to explicit imports, e.g. *.models to home.models -
How does Django's HttpResponse status differ from status_code?
I am trying to set up some custom errors views in a Django application, but I am encountering something I don't quite understand regarding the way HttpResponse works. When I return HttpResponse(status=500) Django does not render the 500.html template. However, when I return using status_code HttpResponse(status_code=500), it works. Here are the steps to my problem: Set up handler500 = views.handler500 Build handler500 view: def handler500(request): return render(request, '500.html', status=500) Try and replicate a 500 error: def cart(request): return HttpResponse(status=500) I am trying to prevent having to refactor hundreds of views in the existing codebase from status=500 to status_code=500. I am worried about breaking something. More importantly, I'm trying to understand the difference between the two. When I read the Django source code for response.py, it seems that they convert status to status_code anyway within class HttpResponseBase. Any and all advice is greatly appreciated. -
django first word of a char field
My model in django has a character field with maximum length 500 character. I'm working with a PostgreSQL database: class Chat(models.Model): message = models.CharField(max_length=500) username = models.CharField(max_length=255) date = models.DateTimeField(auto_now_add=True) @property def first_word(self): return self.message.split(" ")[0] I'm interested to evaluate first word of each message and do some aggregation. First word of each message could vary in length thus I can't use Left, Right or Substr database functions: queryset = Chat.objects.annotate(command=F("first_word")).values("command") .annotate(counts=Count("command")) .order_by("-counts") Obviously my queryset is not working because I can't call model methods in database query. However is there a way I can do this by using some other database functions? -
HTTP response headers in python django-graphene
In our project, we are using bearer tokens for normal programmatic access, but would like to implement basic auth along side for use in graphiql. In order to do this, in the case where neither Bearer or Basic are specified, I want to return www-authenticate response header to cause the browser to request the userid/password for basic auth. Any suggestions how to do this? -
Stock chart transfer between server/website
I'm coding a private webapp that can pick some data from a source (yfinance, panda, ...) and generate a time series. Basically, I want to be able to click on any of the Dow Jones stocks with an HTML btn or whatever, which will send a request to my backend server to generate such chart using python, R or any alternative. Two possibilities: I generate the chart and figures on the client's side, by sending the data from the server to the client on a JSON format (which seems really unproductive). Or, I make all computations on backend, following an HTTP request from the client, generate the chart and send it to the client (my computer). The question is, can I send such chart, from the server to the client without uploading it as a png and transmit the link through AJAX etc. May I get the output of a python function and send it ? To summarize: Can a .png file might be sent from a server to an online webapp, any ideas ? Thanks for your comments, this is a technical question and this might be useful for future requests. Also, I plan to code everything using Django … -
How to filter queryset so all elements in list are matched (at a specific key) in a list of dicts JSONfield?
I have a jsonfield thats an array of dicts all with the same structure. I want to filter that checks whether a given record has all values in a list of params at a specific key, somewhere in the list. (jsonfield) array = [{'dict_field': 1..}, {'dict_field': 2}, {'dict_field': 3}] filter = [1,2,3] return queryset.filter('array__dict_field__contains' = filter) (1 result) filter2 = [1,2,4] return queryset.filter('array__dict_field__contains' = filter2) (0 results; as it doesn't satisfy all filters) I'm using the filter __contains as a placeholder but unfortunately its not contains - what should it be? Thanks I tried array__dict_field__in (example schema above) but it doesn't seem to be working. It doesn't error out but doesn't match any records. The PSQL query it generates is as follows: SELECT * FROM "table" WHERE ("table"."array" -> dict_field) IN (2) This returns an error when I run it in PSQL also; it says column role doesn't exist. I thought it was because role has no quotes on it, but I added them and it persists. Perhaps its because my data is an array of dicts (as opposed to dict) as so: [{"role": 2, "years_experience": 3}, {"role": 3, "years_experience": 5}] Importantly in my case, I can only show a … -
How i can get type of backend in models.py? [Django, social auth]
enter image description here enter image description here My username field is email. The telegram platform does not provide for the presence of email. So, I want to install a stub when logging in via telegram. For this way i need type of used backend. I can't find this information online -
Redirect to the main page if authenticated
I got some problems with redirecting. When I already logged in, and try go to "/accounts/login", it still goes to this link, and if I change in url.py path for example "accounts/logins", the redirect is working, but if not authenticated it says me that: UnboundLocalError: local variable 'context' referenced before assignment AND "/accounts/login" is still available views.py def loginPage(request): if request.user.is_authenticated: return redirect("index") if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'registration/login.html', context) url.py urlpatterns = [ path('login/', views.loginPage, name='loginPage'), path('logout/', views.logoutUser, name='logoutUser'), path('register/', views.registerPage, name='registerPage'), ] -
Django annotating Count/Sum different results
I got the following models: class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class OptaMatch(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) statsperform_id = models.CharField(max_length=255, unique=True) opta_id = models.IntegerField(unique=True) coverage_level = models.IntegerField(default=None, null=True, blank=True) home:OptaTeam = models.ForeignKey(OptaTeam, on_delete=models.CASCADE, related_name="home_opta_matches") away:OptaTeam = models.ForeignKey(OptaTeam, on_delete=models.CASCADE, related_name="away_opta_matches") competition:OptaCompetition = models.ForeignKey(OptaCompetition, on_delete=models.CASCADE, related_name="matches") season:OptaSeason = models.ForeignKey(OptaSeason, on_delete=models.CASCADE, related_name="matches") status = models.CharField(max_length=255, default=None, null=True, blank=True) date = models.DateField(blank=False, null=False) time = models.TimeField(blank=True, null=True, default=None) datetime = models.DateTimeField(blank=True, null=True, default=None) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class OptaEvent(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) opta_id = models.BigIntegerField(unique=True) type_id = models.IntegerField() type_name = models.CharField(max_length=255) period = models.IntegerField(null=True, blank=True, … -
React, data fetched from module (django) isn't being displayed
What's up some guys... I'm having trouble displaying my data, which I fetch from my django modules. Fetching the data seems to work fine, however it won't render and display. Would very much appreciate any help. Right now only the containers and stuff is getting displayed, none of the data from the module. Here is my react component: NewsItemPage.js import "bootstrap/dist/css/bootstrap.min.css"; import React, {Component, useEffect, useState} from "react"; import {useParams} from "react-router-dom"; import {Card, Col, Container, Row} from "react-bootstrap"; import sheet from "./Images/metal-sheet.jpg"; import "./css/newsItem.css"; import {BoxArrowUpRight, Textarea} from "react-bootstrap-icons"; import {Link} from "react-router-dom"; function withParams(NewsItemPage){ return props => <NewsItemPage {...props} params={useParams()}/> } class NewsItemPage extends Component{ state={ item: {}, loading: true } async componentDidMount(){ let {id} = this.props.params; try { const res = await fetch(`http://localhost:8000/api/news/${id}`); const item = await res.json(); this.setState({ item: item, loading: false }) }catch(e){ console.log(e); } } render() { if(this.state.loading){ return <h1 className="text-center">Vänligen vänta...</h1> } console.log(this.state.item); return( this.state.item ? <Container fluid className="news-wrapper "> <Row fluid className="news-page-col"> <Col className="news-page-col text-center mt-5 mb-5"> <h1>{this.state.item.title}</h1> <hr className="divider"/> </Col> </Row> <Row fluid className="gap-5 justify-content-center mt-5"> <Col> <img src={this.state.item.image} alt="image"/> </Col> </Row> <h4>{this.state.item.date}</h4> <Row> <Col> <Textarea>{this.state.item.description}</Textarea> </Col> </Row> </Container> : <h1>Här finns inget ännu...</h1> ); } } export default withParams(NewsItemPage); And … -
Django import-export - Import model with child from excel
I have two models: Project and Activity. When registering a project, one or more associated activities can be added. How can I import projects from xlsx, which include at least one activity?. I'm using the third party library django-import-export I configure the project resource to export all the activities of each project in one cell separated by /, but I need the opposite, import all the activities of each project. I think that I must first save the Project for obtain the id, next extract the info from cell and finally save each activity associated, but I don't know how to do that. My simplified models are: class Project(models.Model): reg_date= models.DateField( default=date.today) name = models.CharField( max_length=100, unique=True) def __str__(self): return self.name class Activity(models.Model): schedule= models.ForeignKey( Project, on_delete=models.CASCADE) date = models.DateField() description = models.TextField(max_length=1000) class Meta: unique_together = ('schedule', 'date', 'description') class ProjectResource(resources.ModelResource): activities = Field() class Meta: model = Project import_id_fields = ['name'] exclude = ('id',) skip_unchanged = True report_skipped = True fields = ('reg_date', 'name', 'activities') def dehydrate_activities(self, obj): if obj.id: return "/".join([ '({0} - {1})'.format(activity.date, activity.description) for activity in obj.projectactivity_set.all() ]) def skip_row(self, instance, original, row, import_validation_errors=None): if original.name: return True return False An example of exported file … -
Django View, foreign key field is killing performance
MyObjects definition: class MyObjects(models.Model): field_a = models.TextField() field_b = models.TextField() ...more irrelevant text/int fields foreign_key_field = models.ForeignKey(AnotherModel, null=True, on_delete=models.SET_NULL) View definition: @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) ...irrelevant logic my_dict = defaultdict(int) for my_obj in objs: ...bunch of irrelevant logic my_dict[str(my_obj.foreign_key_field)] += 1 ...bunch of irrelevant logic return Response(my_dict, status=status.HTTP_200_OK) I do some calculations in my view that are irrelevant and my view takes around 3 seconds for 5000 objects if my_dict[str(my_obj.foreign_key_field)] += 1 is commented out. However, when that line uncommented, my view takes 20seconds. It must be because this field is a foreign key field as none of my other fields are foreign keys. That specific line is the only line referencing that field. How am I able to improve performance on this? I am surprised that just adding this line decreases my performance by that much, as objects is only around 5k and the foreign key table is around 50 objects. No other operations are touching this dictionary because that specific line, so it's not a cascading affect. If I comment out all logic besides that specific line @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) my_dict = defaultdict(int) for my_obj in objs: my_dict[str(my_obj.foreign_key_field)] += 1 return … -
Django not loading fixtures when there is post_save signal
I am testing a registration function in my Django app. When users register, a default user_type is designated to the user. I am using a post_save signal to process this. I have a Profile model to be connected with the User and under the Profile model, is a field user_type which is from another model. class UserType(models.Model): name = models.CharField(max_length=50, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.ForeignKey(UserType, on_delete=models.SET_NULL, null=True, blank=True) To automatically assign a default user_type, I have a signal: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: user_type = UserType.objects.get(pk=1) Profile.objects.create( user=instance, user_type=user_type) I made a fixture of my User, Profile, and UserType models and in my APITestCase, I placed the fixture. class TestUserManagement(APITestCase): fixtures = ['fixtures/initial'] When I run the test, the fixtures does not seem to load to the test database. File "/usr/src/app/fixtures/signals.py", line 15, in create_user_profile user_type = UserType.objects.get(pk=1) ... {model}.UserType.DoesNotExist: Problem installing fixture '/usr/src/app/fixtures/initial.json': UserType matching query does not exist. -
Django Python HTMX - Pagination is not working on multiple tables in one template
I try to build a search which shows four tables with four different models. On that multiple tables I have a problem with my infinite scroll. The output doesn't pay attention on the "paginate_by=5" variable so it just show every result. In addition to that, the pagination only use the first item of the get_template_names. So when I scroll down, it fills the tables with the order table. My views.py: **class searchView(ListView): ordering = ['-id'] template_name = 'search_items.html' paginate_by = 5 model = Rooms def get_template_names(self): if self.request.htmx: return ['single-rows/search_orders_single_row.html', 'single-rows/search_products_single_row.html', 'single-rows/search_rooms_single_row.html', 'single-rows/search_suppliers_single_row.html'] return 'search_items.html' def get_context_data(self, **kwargs): searchedItem = self.request.GET.get('searchedItem',default="") context = super(searchView, self).get_context_data(**kwargs) context['all_orders'] = Orders.objects.all() context['all_products'] = Products.objects.all() context['all_suppliers'] = Suppliers.objects.all() context['rooms'] = Rooms.objects.filter(Q(room__contains=searchedItem) | Q(cabinetNumber__contains=searchedItem) | Q(shelf__contains=searchedItem)) #filtered_rooms get the results from the search in the database context['products'] = Products.objects.filter(Q(designation__contains=searchedItem) | Q(category__contains=searchedItem)) context['orders'] = Orders.objects.filter(Q(product__contains=searchedItem) | Q(supplier__contains=searchedItem)) context['suppliers'] = Suppliers.objects.filter(Q(s_name__contains = searchedItem)) context['searchedItem'] = searchedItem return context** my search-template: <div class="col-6 col-s-6 table"> {% if searchedItem %} <h1>Suchergebnisse für: {{ searchedItem }} </h1> {% if rooms or products or orders or suppliers %} {% if rooms %} <p>Suchergebnisse in "Räume"</p> <table class="content"> <thead> <tr> <th>Raum</th> <th>Schranknummer</th> <th>Regalfach</th> <th>Aktion</th> </tr> </thead> <tbody> {% include 'single-rows/search_rooms_single_row.html' %} </tbody> … -
Managing python path and version for Django using mod_wsgi
I've joined the unhappy ranks of people who have tried to set up a Django website served by Apache (on Amazon-linux EC2). I have successfully configured Apache and compiled mod_wsgi against Python3.4 using a virtualenv (at /home/ec2-user/web-dev) largely following instructions at https://gist.github.com/tanuka72/79ae58b16be4ac3fafe0 and the mod_wsgi docs). However, I get an Internal Server Error when loading the Django test app. Looking at the logs, it seems that multiple versions of Python are somehow being called during the processing (see the change from /home/ec2-user/web-dev/lib64/python3.4 to /usr/lib64/python3.7). Also it seems that mod_wsgi cannot be imported (whilst 'import mod_wsgi' works fine from a python prompt in the ec2 terminal). [Thu Jan 19 15:19:27.329376 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Failed to exec Python script file '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.329445 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Exception occurred processing WSGI script '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.330049 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] Traceback (most recent call last): [Thu Jan 19 15:19:27.330088 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/var/www/test/test_site/test_site/wsgi.py", line 25, in <module> [Thu Jan 19 15:19:27.330093 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] application = get_wsgi_application() [Thu Jan 19 15:19:27.330108 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/home/ec2-user/web-dev/lib64/python3.4/site-packages/django/core/wsgi.py", line 12, … -
Django Rest API complain about swagger version
We are using DJango rest framework to make api. We added swagger page, but its complain about swagger version. Unable to render this definition The provided definition does not specify a valid version field. Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0). I was following documentation https://www.django-rest-framework.org/topics/documenting-your-api/#a-minimal-example-with-swagger-ui Below are files. urls.py from django.urls import path urlpatterns = [ ... ... path("openapi", get_schema_view( title="My api", description="API for me", version="1.0.0" ), name="openapi-schema"), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui') ] templates/swagger-ui.html <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> I think, its complaining about version: 1.0.0 mentioned in openapi schema view. But need to sure, if something else is not causing this issue. -
Is there a way to show only some model fields?
I have a model with field instances and have views. Can i make so that when you redirect to to main page you can see only ID, title, deadline, done? But when you redirect to the detail page you can see all the model fields. models.py: class Task(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.TextField() deadline = models.DateTimeField() done = models.BooleanField() views.py : lass TaskList(generics.ListCreateAPIView): # permission_classes = (IsAuthorOrReadOnly,) queryset = Task.objects.all() serializer_class = TaskSerializer class TaskDetail(generics.RetrieveUpdateDestroyAPIView): # permission_classes = (IsAuthorOrReadOnly,) queryset = Task.objects.all() serializer_class = TaskSerializer serializers.py: class TaskSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "title", "body", "author", "deadline", "done", ) model = Task urls.py: urlpatterns = [ path("<int:pk>/", TaskDetail.as_view(), name="task_detail"), path("", TaskList.as_view(), name="task_list"), ] Please add a link to useful reading materials -
'AgencyRegistration' object has no attribute 'get'
I'm trying to create an endpoint using Django REST framework, but when I'm trying to get the data from the endpoint I'm getting the following error: AttributeError: 'AgencyRegistration' object has no attribute 'get'. Here's my code models.py `class AgencyRegistration(models.Model): agency_name = models.CharField(max_length=200) tax_id_number = models.IntegerField(max_length=12) address_street = models.CharField(max_length=220) city = models.CharField(max_length=50) county = models.CharField(max_length=50) state = models.CharField(max_length=100) zip_code = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) title = models.CharField(max_length=200) email = models.CharField(max_length=200) phone = models.CharField(max_length=50) children_amount = models.CharField(max_length=100) age_range = models.CharField(max_length=100) program_benefit = models.CharField(max_length=200) organization_type = models.CharField(max_length=200) how_did_you_hear = models.CharField(max_length=200) def __str__(self): return self.agency_name` views.py `def agency_registration(request): agency_data = AgencyRegistration.objects.all() serializer = AgencyRegistrationSerializer(agency_data, many=True) return render(JsonResponse(serializer.data, safe=False))` serializers.py `class AgencyRegistrationSerializer(serializers.ModelSerializer): class Meta: model = AgencyRegistration fields = [ 'id', 'agency_name', 'tax_id_number', 'address_street', 'city', 'county', 'state', 'zip_code', 'first_name', 'last_name', 'title', 'email', 'phone', 'children_amount', 'age_range', 'program_benefit', 'organization_type', 'how_did_you_hear' ]` urls.py `urlpatterns = [ path('agency-registration/', views.AgencyRegistration), ]` -
django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple after upgrading Django
Hi I upgrade the django and after that I'm getting this error django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple. but in my setting.py file the ALLOWED_HOSTS is already in the list config.py DJANGO_CONFIG = { 'secret_key': 'fadfas-------', 'debug': False, 'admin_module': True, 'allowed_hosts': '[\'*\']', 'server_host': 'http://127.0.0.1:8000', } setting.py ALLOWED_HOSTS = DJANGO_CONFIG['allowed_hosts'] -
How to integrate third party api's in Django?
I have a project that works as a single login and I must integrate other apis so that they can log in to this api and return to their logged-in api of origin. Any help or information on the subject will be appreciated. -
How to insert data inside the html tag by fetching from django database?
is it possible in django to fetch data from database and insert it inside the html tag. I've created a below model and I want to put its data into respective html tags. class Metadata(models.Model): meta_name = models.CharField() meta_desc = models.TextField() meta_key = models.TextField() views.py def func(request): desc = Metadata.objects.get(meta_desc="some text") desc_k = Metadata.objects.get(meta_key="some text") return render(request, "results.html", {'desc':desc,'desc_k':desc_k}) I want to fetch this meta_desc and meta_key data and insert it into below HTML tags respective to its matching meta_name. I tried above function but its not working, I guess either its not possible to do that or i'm doing it wrong. results.html <meta name="description" content=" {{ desc.meta_desc }}"> <meta name="keywords" content="{{ desc_k.meta_key }}"> Please suggest me if there is any other way to do this? Thanks -
Using django form wizard with allauth
Currently my user sign up process is implemented with allauth. Does anyone have any experience of how to make this a multipage process e.g. with form wizard from formtools? forms.py (stored at users/forms.py) class UserCreationForm1(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) username = CharField(label='User Name', widget=TextInput(attrs={'placeholder': 'User Name'}) ) class Meta(forms.UserCreationForm.Meta): model = User fields = ['username', 'email', 'title', 'first_name', 'last_name', 'country', ] field_order = ['username', 'email', 'title', 'first_name', 'last_name', 'country', ] def clean_username(self): username = self.cleaned_data["username"] if self.instance.username == username: return username try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) class UserCreationForm2(forms.UserCreationForm): class Meta(forms.UserCreationForm.Meta): model = User fields = ['occupation', 'password1', 'password2', 'terms'] field_order = ['occupation', 'password1', 'password2', 'terms'] def clean_terms(self): is_filled = self.cleaned_data['terms'] if not is_filled: raise forms.ValidationError('This field is required') return is_filled For the views.py i then have SIGNUP_FORMS = [('0', UserCreationForm), ('1', UserCreationForm2)] TEMPLATES = {'0': 'account/signup_1.html', '1': 'account/signup_2.html'} class SignupWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): for form in form_list: if isinstance(form, UserCreationForm): print('form1') user = form.save(self.request) elif isinstance(form, UserCreationForm2): userprofile = form.save(commit=False) user = self.request.user userprofile.user = user userprofile.save() print('form2') return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) What I find though is that after completing the …