Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting trouble while deploying Django ASGI application on ubuntu server. NGINX has been used as webserver
I am facing a lot of trouble while deploying my Django ASGI application. I have tried all the solutions out there. In my ngix/error.log file, the error is: 2020/11/05 21:37:48 [error] 6716#6716: *31 connect() failed (111: Connection refused) while connecting to upstream, client: 103.144.89.98, server: 156.67.219.10, request: "GET /ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/ HTTP/1.1", upstream: "http://[::1]:9001/ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/", host: "156.67.219.10" In web-browser console, I am getting the following error: WebSocket connection to 'ws://156.67.219.10/ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/' failed: Error during WebSocket handshake: Unexpected response code: 400 Here is my settings.py file: WSGI_APPLICATION = 'thinkgroupy.wsgi.application' ASGI_APPLICATION = "thinkgroupy.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } Here is the file of nginx configuration: /etc/nginx/sites-available/thinkgroupy: #added this block upstream channels-backend { server localhost:9001; } server { listen 80; server_name 156.67.219.10; client_max_body_size 4G; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin/thinkgroupy/staticfiles/; } location /media/ { root /home/admin/thinkgoupy; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } #path to proxy my WebSocket requests location /ws/ { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; } } Here is the supervisor file: /etc/supervisor/conf.d/thinkgroupy.conf: [program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:9001 # Directory … -
Hackathon preparation [closed]
I have a hackathon coming up, although it is not really specified what we will be doing. My team and I have decided on building a web application. How best can we allocate the work between 3 people and work efficiently to make a great application within 24 hours -
Deploying Django web app - 503 Service Unavailable
I'm trying to deploy a Django web application. I'm deploying it using cPanel and the functionality "Setup Python App". The application is working on localhost on my machine. However, when deployed I keep getting a 503 error saying Service Unavailable! The server is temporarily busy, try again later! I have added my domain name into the ALLOWED_HOSTS list in settings.py, so that's not the issue. I have also tried deploying an empty Django app but the result was the same. Using an SSH connection, I tried running python manage.py runserver and there were no issues. Therefore, I guess the problem is not in the app. After an attempt to the URL I get the following in the error log: 2020-11-04 18:49:21.400909 [INFO] [2117345] [<ip>#APVH_www.<domain_name>.com:443] connection to [uds://tmp/lshttpd/APVH_www.<domain_name>.com:443:Django_Project-master_.sock] on request #0, confirmed, 0, associated process: 0, running: 0, error: No such file or directory! 2020-11-04 18:49:21.400923 [INFO] [2117345] [<ip>#APVH_www.<domain_name>.com:443] connection to [uds://tmp/lshttpd/APVH_www.<domain_name>.com:443:Django_Project-master_.sock] on request #0, confirmed, 0, associated process: 0, running: 0, error: No such file or directory! 2020-11-04 18:49:21.400929 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] Max retries has been reached, 503! 2020-11-04 18:49:21.401018 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] oops! 503 Service Unavailable 2020-11-04 18:49:21.401020 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] Content len: 0, Request line: 'GET /djangotest/ HTTP/1.1' … -
404 Error: unable to serve static react build with django rest framework, unless I go to /index.html
I have a React front end that I turned into static files. I used npm run build to make the folder. Then I configured my Django Rest Framework: settings.py FRONTEND_ROOT = os.path.abspath(os.path.join(BASE_DIR, '..', 'frontend', 'build')) urls.py re_path(r'^(?P<path>.*)$', serve, { 'document_root': settings.FRONTEND_ROOT }), when I got to the localhost:8000, I get a 404 page. If howerver, i got to localhost:8000/index.html, then I dont get a 404 but the react app. The css and html are not loaded though. Is this a proper way to connect the static react to my django backend? Am I missing a step? -
Find an object in Django using a list inside JSONField
I have such a model in Django: class Event(models.Model): EVENT_TYPE_CHOICES = [(e, e.value) for e in EVENT_TYPE] event_type = models.TextField(choices=EVENT_TYPE_CHOICES) date_of_event = models.DateTimeField(default=timezone.now, db_index=True) event_data = JSONField() And there is the event_data JSONField there which has the following structure: 'project_id': project_id, 'family_id': family_id, 'variant_data': variant_data_list, 'username': user.username, 'email': user.email, Where variant_data_list is a list of such dict objects with 3 str values: {'xpos': xpos, 'ref': ref, 'alt': alt} Now, I need a way to find unique Event model object based on the supplied variant_data_list (each object inside of it should be found within a single Events' variant_data_list, is it possible to achieve somehow? The number of items in variant_data_list is from 1 to 3. Otherwise I am thinking of generating unique ids based on the variant_data_list each time it is written to postgres (but not sure how to make it either). Any suggestions would be greatly appreciated. -
django custom user field won't appear in admin form
I created a custom user model in django with an additional field. However although I can see it appear in the list view in Django's admin it won't appear in the form to create or update a user, even though I've amended these. models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # Need to support codes with leading 0, hence CharField secret = models.CharField(max_length=5) def __str__(self): return self.username forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email', 'secret') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'secret') admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'secret'] admin.site.register(CustomUser, CustomUserAdmin) -
Error when I delete instances in the django panel
I created a duplicate function in order to create a new and equal instance from an other. But when I try to delete the instance the next error appears: FOREIGN KEY constraint failed What must I do in my function for to solve it? My duplicate function is: def duplicate(scn): id_original = scn.id scn.id = Scenario.objects.order_by('id')[Scenario.objects.all().count()-1].id + 1 scn.name = scn.name + '_dup' scn.save() #ahora scn es el nuevo scn_original = Scenario.objects.filter(id=id_original)[0] return None -
Do I need different URLs for options for years selected to play a game? Made with python3 and Django
I'm trying to make a game with Django where you can select different episodes of a game show to play, and have a database with different episodes over the years. I want to have the user select the year, month, and specific episode that they want to play. If the years are 1990-2000, would I need to have a different URL (for example in urls.py: path('years/1997', views.1997, name = 'game-1997', repeat for all 1990-2000) in the list in Django for each year and access that with a get/post, or is there a way to just carry the selected year onto the page listing the months, and have that be used as a parameter for which set of months to display? For context, the code below would be what I would have in my views.py if I don't need to have a different page URL for each possible year: def months(request): request.GET.get('year_choice') episodes = clues.objects.order_by('airdate').distinct('airdate') months = [] for episode in episodes: episode.airdate = episode.airdate[6:7] month = calendar.month_name[int(episode.airdate)] if month not in months: months.append(month) context = { 'months': months } return render(request, 'game/months.html', context) If this doesn't make sense, please feel free to ask any questions. This is my first time … -
How to add limit to the line break in django template filter?
Here i am trying to add some filters to the post body content, I am using safe filter and truncatechars filter and i also want to use linebrake filter , if there is a single line break than don't show the content after that line break or if the number of chars exceed to the 200 than just show 200 hundred char if there is no line break. if the line break is after 50 chars than just show 50 chars i want to do the following thing but obvious right now this is wrong and showing me an error <p class="small text-muted">{{post.body|safe|truncatechars:200|linebreaksbr:1}}</p> -
'ascii' codec can't encode character '\u2019' in position 36: ordinal not in range(128)
i working on email confirmation in django, i want make token with PasswordResetTokenGenerator: tokens.py class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp) + text_type(user.is_active)) account_activation_token = TokenGenerator() views.py class Register(CreateView): form_class = SignupForm template_name = 'registration/register.html' def form_valid(self, form): if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mail_subject = 'Activate your blog account.' message = render_to_string('registration/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') and i get this error: Traceback (most recent call last): File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\edit.py", line 172, in post return super().post(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\user1\Desktop\config\mysite\account\views.py", line 63, in form_valid email.send() File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\backends\smtp.py", line 69, in open self.connection.login(self.username, … -
db service connection error when Docker Compose Up
Right now I am working on containerize my Python django app with docker. I has two services in docker-compose file: web and db. And web service depends on the db service. While I ran docker-compose build is fine but when I ran docker-compose up, the web service always error out with error: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 … -
Django not detecting foreign key in a ManyToManyField when passed through a Model
I am trying to build a relation between the Subject model and the Teacher model and the Classes model. This is how I am relating it- A subject can be taught in many classes and a class can have many subjects. A subject in a class can be taught by only one teacher. So basically what I am trying to do is this- there's a subject, say Maths, the subject can be taught in many classes, say Class 1 to Class 10 and there will be various teachers teaching in different classes. Here's my Subject model: class Subjects(models.Model): subject_id = models.CharField(unique=True, max_length=20) classes = models.ManyToManyField(Classes, through='ThroughTeacher') ThroughTeacher model: class ThroughTeacher(models.Model): class_id = models.ForeignKey(Classes, null=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(Teacher, null=True, on_delete=models.SET_NULL) Classes model: class Classes(models.Model): class_id = models.CharField(unique=True, max_length=30) teacher = models.ManyToManyField(Teacher) Teacher model: class Teacher(models.Model): name = models.CharField(max_length=30) contact = models.CharField(max_length=10) This is the error I am getting: subjects.ThroughTeacher: (fields.E336) The model is used as an intermediate model by 'subjects.Subjects.classes', but it does not have a foreign key to 'Subjects' or 'Classes'. -
How I can save a list of string in my model?
I want to store a list of strings as a field of my model. categories=['Abstract Strategy', 'Medieval'] I want to save the category as a field. my database is sqlite3. -
Can I limit the displaying of Django's Page not found?
When I develop Django websites, I always develop them on a server that sits on the Internet in order to mirror my production environment (I run macOS locally but my servers are Linux). During development I also will set DEBUG = True for debugging purposes. The problem is that if I or anyone else who's poking around on my site enters an invalid URLconf string, Django displays the "Page not found (404)" page along with all valid URL patterns, which I feel is a bit of a security risk. For example, my custom URL for the Django admin site is listed there. Is there a way to disable the showing of this specific error page when I have DEBUG set to True or perhaps to limit its display to particular IP addresses? -
ValueError at /sendrequest/bandit Cannot assign "'jacob'": "ConnectRequest.sender" must be a "Profile" instance
i am making a friend request feature and i am not able to save my data this error is showing up everytime. this is my views.py def sendrequest(request,receiver): receiver_user = Profile.objects.get(username=receiver).username sender=request.user sender_user=Profile.objects.get(username=sender).username connection=ConnectRequest(sender=sender_user, receiver=receiver_user, status="Pending" ) connection.save() return redirect("buddylist") this is my Profile model class Profile(models.Model): idno=models.AutoField(primary_key=True) name=models.CharField(max_length=30) email=models.CharField(max_length=40) username=models.CharField(max_length=30) this is my ConnectRequest model class ConnectRequest(models.Model): sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(Profile,on_delete=models.CASCADE, related_name="receiver") choice=( ("Accepted","Accepted"), ("Declined","Declined"), ("Pending","Pending") ) status=models.CharField(max_length=10,choices=choice,blank=True) def __str__(self): return f"{self.sender} to {self.receiver} status {self.status}" -
How to create a new HTML li upon creation a new page in Django
I have created a new model and added it to the admin page so the admin can add new pages via /admin section. Now I need to add every page which is created to the html footer as a new home.html (footer section) <div class="col-md-6 col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Home</a></li> <li><a href="#">Services</a></li> <li><a href="#">Events</a></li> <li><a href="#">Team</a></li> <li><a href={{ footer.faq }}>FAQ</a></li> <li><a href={{ footer.terms_and_conditions }}>Terms & Conditions</a> {% for i in context %} <li>{{i.title}}</a> {% endfor %} </li> </ul> </div> </div> </div> I tried to loop through in every new page created views.py def custom_page(request, slug): context = { 'all': CustomPage.objects.filter(slug=slug), 'toBePublished': CustomPage.objects.all() } return render(request, 'member/custom_page.html', context) models.py class CustomPage(models.Model): title = models.CharField(max_length=20, blank=True) subtitle = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=500,blank=True) content = RichTextField() displayOnFooter = models.BooleanField(default=False) def __str__(self): return f'{self.title}' def get_absolute_url(self): return reverse('custom-page', kwargs={'slug': self.slug}) I have successfully created the slug so when a new page is created via admin I can find it via / but cannot seem to add it into the footer. Thanks Onur -
unable to upload image in folder using django
trying to upload image in folder a name 'pics' but after successful submision of form Just url of the image is stored in database column but there isn't any image in pic's folder stored. please help me to store images in pics folder using form. thank you. here is html <form id="form1" action='/indexpage' method="POST"> {% csrf_token %} <div id="jQueryProgressFormBar"></div> <div id ='part1'> <div class="row"> <div class="input-group col-6 ml-0 pl-0 m-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01">Upload</span> </div> <div class="custom-file"> <input type="file" name='img' class="custom-file-input" id="upload"> <label class="custom-file-label" for="inputGroupFile01" id="inputGroupFile02">Choose file</label> </div> </div> </div> <div class="row"> <div class="col-sm"> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label pr-3">Session:</label> <div class="col-sm-10"> <select class="form-control" name="session"> <option value='2019-2022'>2019-2022</option> <option value='2020-2023'>2020-2023</option> <option value='2021-2024'>2021-2024</option> </select> </div> </div> </div> </form> main URL's from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url urlpatterns = [ path('', include('index.urls')), url(r'^accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ TEMPLATE_DIR, ] STATIC_ROOT ='/home/manteeform/Projects/manteeform/staticfiles' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" models.py from django.db import models class Student_personal(models.Model): session = models.CharField(max_length=12) img = models.ImageField(upload_to='pics') clas = models.CharField(max_length=15) -
Django ON_DELETE policy not being applied in DB
I have the following model: class GeneMiRNACombination(models.Model): gene = models.CharField(max_length=50) experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE) source_statistical_data = models.OneToOneField( SourceDataStatisticalProperties, on_delete=models.SET_NULL, blank=True, null=True, default=None ) So I'd expect tha the ON_DELETE will be setted in the DB (Postgres in my case). But when I see the CREATE script this is what it prints: CREATE TABLE public.gene_mirna_combination ( id integer NOT NULL DEFAULT nextval('gene_mirna_combination_id_seq'::regclass), gene character varying(50) COLLATE pg_catalog."default" NOT NULL, experiment_id integer NOT NULL, source_statistical_data_id integer, CONSTRAINT gene_mirna_combination_pkey PRIMARY KEY (id), CONSTRAINT gene_mirna_combination_properties_id_key UNIQUE (source_statistical_data_id), CONSTRAINT gene_mirna_combinati_experiment_id_31b52a17_fk_api_servi FOREIGN KEY (experiment_id) REFERENCES public.api_service_experiment (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT gene_mirna_combinati_source_statistical_d_7d0f04a8_fk_statistic FOREIGN KEY (source_statistical_data_id) REFERENCES public.statistical_properties_sourcedatastatisticalproperties (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) TABLESPACE pg_default; ALTER TABLE public.gene_mirna_combination OWNER to root; CREATE INDEX gene_mirna_combination_experiment_id_31b52a17 ON public.gene_mirna_combination USING btree (experiment_id ASC NULLS LAST) TABLESPACE pg_default; So, there is no action on delete! Why? It should set the ON DELETE CASCADE when creates the table, shouldn't it? Is there any implicit behaviour? If there isn't an ON DELETE policy so every time I remove a referenced object it must be removed from Django, which will be extremely slower than … -
Is it okay to call django functions through an API?
I'm building a project and now I'm new to VueJS I'm currently learning it. and I found that you can make HTTP Requests on APIs using axios. And to make my project easy, Can I call functions on my views.py thru axios? Like I'm fetching urls in urls.py to execute some functions on my backend. Is it okay? I mean for security and best practices. etc. Thanks -
Authentication problem using Nginx and Django Rest Framework
When trying to create a Django Rest Framework based web app, we encountered the following problem: Our whole app should and is protected by our settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ), But for one single route (which provides the schema for the front end code generation) we would like to have basic auth (test:test@host/special_route). The idea was to add the route to nginx like here. Our nginx conf looks as follows: server { ... location /special_route { auth_basic "API Schema"; auth_basic_user_file /etc/nginx/.htpasswd; } } Now when accessing this route the authentication popup shows and the password and username are validated, but on success it shows 404. When deleting this piece of code it shows up without the 404, so I am guessing it's not a Django problem. I tried adding basic authentication to the auth classes, reloading and restarting the server and changing the special_route to avoid misspells. I even experimentally deleted the location and applied the config to the whole server, which worked as expected. -
appending the data according "id" : Python
I'm getting the "km_difference" data in a dictionary of list format in another list. but i want to get the "km_difference" data inside the first index of list according it's "id". Any helpful, would be much appreciated. thank you so much in advance. data = ShopOwnerShopDetailsSerializer(garage_qs, many=True, context={'request': request}).data km_difference = [] for record in data: lon = record['lon'] lat = record['lat'] lon1 = float(lon) lat1 = float(lat) km_differ = distance(lon1, lat1, lon2, lat2) km_difference.append({"km_difference":km_differ}) data.append({"km_difference":km_difference}) Result: how i get the data format is: { "message": "success", "search_result": 2, "data": [ { "id": 2, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", }, { "id": 5, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", }, { "km_difference": [ { "km_difference": 7853.450620509551 }, { "km_difference": 7853.450620509551 } ] } ] } Expecting: how i want output on this format is: { "message": "success", "search_result": 2, "data": [ { "id": 2, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", "km_difference": 7853.450620509551 }, { "id": 5, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", "km_difference": 7853.450620509551 }, ] } -
Redirect to the another html page after clicking input tag in django template
I want to redirect the website after edit (http://127.0.0.1:8000/account/edit/) to the dashboard (http://127.0.0.1:8000/account/dashboard) in Django template. I have a file named dashboard.html in the same directory. But it keeps me to the same page (http://127.0.0.1:8000/account/edit/. edit.html {% extends "base.html" %} {% block title %}Edit your account{% endblock %} {% block content %} <h1>Edit your account</h1> <p>You can edit your account using the following form:</p> <form action="dashboard.html" method="post" enctype="multipart/form-data"> {{ user_form.as_p }} {{ profile_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save change"></p> </form> {% endblock %} -
Ignoring duplicate records when using bulk create
I have implemented and endpoint that is used to read a csv or an excel file and seeds the records into the database as shown below. How do I ensure that I don't upload duplicates into the database? def post(self, request, *args, **kwargs): """Upload the CSV file. Then reads it and saves *.csv *.xlsx data to database. Endpoint: /api/import_data/ """ print(request.data['file'].__dict__) file_serializer = FileSerializer(data=request.data) # Commented code is for debugging only # import pdb; pdb.set_trace() # print(to_dict['_name']) _dict_file_obj = request.data['file'].__dict__ _csv = _dict_file_obj['_name'].endswith('.csv') _excel = _dict_file_obj['_name'].endswith('.xlsx') if request.data['file'] is None: return Response({"error": "No File Found"}, status=status.HTTP_400_BAD_REQUEST) csv_data = self.request.data.get('file') if file_serializer.is_valid(): data = self.request.data.get('file') if _csv is True: print('Show') data_set = data.read().decode('UTF-8') io_string = io.StringIO(data_set) io_string = io.StringIO(data_set) csv_file = pd.read_csv(io_string, low_memory=False) columns = list(csv_file.columns.values) first_name, last_name, email = columns[0], columns[1],\ columns[2] instances = [ Business( business_id=row[0], business_name=row[1], business_activity=row[16], pin_number=row[29], activity_code=row[21], town=row[33], physical_address = row[8], po_box=row[31], sub_county_code=row[22], ward_code=row[23], plot_number = row[9] ) for index, row in csv_file.iterrows() ] result = Business.objects.bulk_create(instances) serialize= IssuedPermitSerializer(result,many=True) return Response(data=serialize.data) ........................... -
ValueError at /sendrequest/jacob Cannot assign "'jacob'": "ConnectRequest.receiver" must be a "User" instance
i am making a friend request feature and i got this error this is my models.py for friend request class ConnectRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(User,on_delete=models.CASCADE, related_name="receiver") choice=( ("Accepted","Accepted"), ("Declined","Declined"), ("Pending","Pending") ) status=models.CharField(max_length=10,choices=choice,blank=True) this is my urls.py def sendrequest(request,receiver): sender=request.user connection=ConnectRequest(sender=sender,receiver=receiver,status="Pending") connection.save() return redirect("buddylist") -
How to show data by formatting string into django templates?
Here i am creating a blog and formatting some content bold as show below: on a detail page that text is showing me like this: how to fix it and change its format ,