Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reload page while keeping FormGroup content alive
I have got a filter function in a sidenav in my application which filters the list of profiles. However when I submit the filter function in the HTML I call this onFilterButtonSubmit function (see below) which should give my profile-list.component.ts the parameters while also reloading the page. onFilterButtonSubmit(minA, maxA, gen): void { this.profileService.minAge = minA; this.profileService.maxAge = maxA; this.profileService.gender = gen; this.router.navigate(['/home']); } The site is not being reloaded though. Only when I am on another page (f.e. profile-page), parsing the filter criteria and clicking on Filter, it correctly reroutes me to /home and displays the results I filtered for. I also tried using window.location.reload(); which reloads the page successfully but does not save the FormField content. I am kinda lost here, any help is appreciated. Not sure which other code parts are relevant but let me know and I will add it to the question. I am using Angular and Django for the backend. app.component.ts export class AppComponent implements OnInit { title = 'frontend'; isLoggedIn = false; filteredFormControl: any = new FormControl(''); filteredProfilesFormGroup: FormGroup; profiles: Profile[]; public isFiltered: boolean; constructor(public userService: UserService, public profileService: ProfileService, private router: Router) { } ngOnInit(): void { this.filteredProfilesFormGroup = new FormGroup({ minAge: new … -
Change the Django Rest Framework Default Router api root?
In development, my defaultrouter works along the base url/domain of http://127.0.0.1:8000/, however the api is going to be hosted on http://website.com/test/location/ How do i change the default default router location so apiview,inner links, and the api work at http://website.com/test/location/ as the api root? -
Is there a way to reference variable name as a string in that variable's declaration in Python?
For my Django application, I have a dictionary of field names (keys) mapped to help texts (values) (which I read in from a csv file). In models.py, I want to retrieve the appropriate help text for each field name. If I have a sample dictionary like the following, with an entry for each field: test_dict = { 'host_name': 'The name of a host', ... } And my models.py looks like this: class Host_main(models.Model): host_name = models.CharField(max_length=20, unique=True, help_text=test_dict['host_name']) def __str__(self): return self.host_name Is there a way to call the variable name (host_name) dynamically in each help_text definition? I do have the option to do something like the following: from varname import nameof host_name = models.CharField(max_length=20, unique=True, help_text=test_dict[nameof(host_name)]) But if possible, I'd like to reference the current variable name with something consistent to avoid typing out the field name a second time, like help_text=test_dict[nameof(**this**)] in pseudocode. Thanks! -
Django AssertionError at /search/
I have an issue when I try to search for a second time. I will get the results from the first search, however, when I want to search for a different field I'm getting AssertionError. I'm not sure how can I fix this error. Any help is appreciated. def search(request): queryset_list = Oglas.objects.order_by('-list_date')[:5] # keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains = keywords) # Area if 'area' in request.GET: area = request.GET['area'] if area: queryset_list = queryset_list.filter(area__iexact = area) # rooms if 'bedrooms' in request.GET: bedrooms = request.GET['bedrooms'] if bedrooms: queryset_list = queryset_list.filter(bedrooms__lte=bedrooms) -
Django annotated queryset with latest values for some fields
I have a model which store some marketing performances: class DailyPerformance(models.Model): class Meta: unique_together = ('route_hash_value', 'datetime_tz') ordering = ('-datetime_tz',) route_hash_value = models.CharField(max_length=255, db_index=True, editable=False) datetime_tz = models.DateTimeField(db_index=True, editable=False) network = models.ForeignKey('administration.Network', on_delete=models.PROTECT, null=True) account = models.ForeignKey('administration.Account', on_delete=models.SET_NULL, null=True) # Properties budget = models.FloatField(null=True, db_index=True) bid = models.FloatField(null=True, db_index=True) status = models.CharField(max_length=255, null=True, db_index=True) # METRICS cost_amount = models.FloatField(null=True, db_index=True) impressions = models.IntegerField(null=True, db_index=True) clicks_in = models.IntegerField(null=True, db_index=True) clicks_out = models.IntegerField(null=True, db_index=True) revenue_amount_net = models.FloatField(null=True, db_index=True) _profit = models.FloatField(null=True, db_index=True) _roi = models.FloatField(null=True, db_index=True) _ctr = models.FloatField(null=True, db_index=True) And I need to generate a queryset for the drf ModelViewset which aggregate numeric metrics and get the last values for the fields: bid, budget and status. Something like this: class DailyPerformanceHViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): queryset = DailyPerformance.objects.values( 'route_hash_value', 'datetime_tz', 'network', 'account', ).annotate( cost_amount=Round(Sum('cost_amount'), 3), revenue_amount_net=Round(Sum('revenue_amount_net'), 3), impressions=Sum('cost_impressions', output_field=FloatField()), clicks_in=Sum('cost_clicks_in', output_field=FloatField()), clicks_out=Sum('cost_clicks_out', output_field=FloatField()), _profit=Round(Sum('_profit'), 3), _roi=Round(F('_profit') / F('cost_amount'), 3), _ctr=Round(F('clicks_out') / F('clicks_in'), 3), ### budget=..., # <== LATEST BUDGET ORDERED BY -datetime_tz bid=..., # <== LATEST BID ORDERED BY -datetime_tz status=..., # <== LATEST STATUS ORDERED BY -datetime_tz ) return queryset but I really don't know how to do that -
gunicorn.service: Failed to determine user credentials: No such process
I keep getting an error when trying to set gunicorn with my django project ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-02-04 17:45:34 +01; 25min ago TriggeredBy: ● gunicorn.socket Main PID: 754981 (code=exited, status=217/USER) Feb 04 17:45:34 vps141106 systemd[1]: Started gunicorn daemon. Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed to determine user credentials: No such process Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Start request repeated too quickly. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: Failed to start gunicorn daemon. This is my service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/root/test ExecStart=/home/root/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ test.wsgi:application [Install] WantedBy=multi-user.target Im getting those errors gunicorn.service: Failed to determine user credentials: No such process gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process Now Im pretty sure I have something in /home/root/venv/bin/gunicorn I just did a nano /home/root/venv/bin/gunicorn and … -
Django import from csv(update_or_create)
my program loads data from csv (customoer, item, total), here is my data model: from django.db import models class Member(models.Model): customer = models.CharField(max_length=50) item = models.JSONField(max_length=50) total = models.IntegerField() def __str__(self): return self.customer My view: def upload(request): template = 'upload.html' promt = { 'member': 'Member of CSV should be customer, item, total' } if request.method == 'GET': return render(request, template, promt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Member.objects.update_or_create( customer=column[0], item=column[1], total=column[2] ) context = {} return render(request, template, context) In general, the download works, but instead of updating the user data, a new object is created with the same customer, how can I make it so that a new customer is not created, but only the total and item are updated in it? Example CSV data: customer,item,total bellwether,Cavorit,6126 resplendent,Saphire,8502 bellwether,Ruby,342 Instead of not creating two or more objects with the bellwether customer, there was only one object with customer bellwether an item ("Kavorit", "Ruby"), total (6468). Thank you for your time -
Django "Class 'User' has no 'objects' Member" pylint(no-member) [30, 16]
I'm new to Django, and I got some issue with views.py. I'm not sure why but there is error at User model. I tried to install pylint using pip install pylint-django and wrote {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],} in my vsCode setting. But it doesn't work. Can anyone help me to solve this issue? This is my code for models.py and views.py models.py: class User(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username views.py: from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.shortcuts import render from stream_chat import StreamChat from .models import User # this decorator marks a view as being exempt from the protection ensured by the middleware @csrf_exempt def init(request): if not request.body: return JsonResponse(status=200, data={'message': 'No request body'}) body = json.loads(bytes(request.body).decode('utf-8')) if 'username' not in body: return JsonResponse(status=400, data={'message': 'Username is required to join the channel'}) username = body['username'] client = StreamChat(api_key=settings.STREAM_API_KEY, api_secret=settings.STREAM_API_SECRET) channel = client.channel('messaging', 'General') try: user = User.objects.get(username=username) token = bytes(client.create_token( user_id=user.username)).decode('utf-8') return JsonResponse(status=200, data={"username": user.username, "token": token, "apikey": settings.STREAM_API_KEY}) except User.DoesNotExist: user = User(username=username) user.save() token = bytes(client.create_token( user_id=username)).decode('utf-8') client.update_users({"id": username, "role": "admin"}) channel.add_members([username]) return JsonResponse(status=200, data={"username": user.username, "token": token, "apiKey": settings.STREAM_API_KEY}) Thank you -
How to work with Ajax in Django Admin Panel?
I have a ForeignKey relation between project and projectfloorplan, and my project model has multiple projectfloorplan. Now I have created a new section for Property and the property have ForeinKey relation with Project, Now if I select any project from the dropdown then the project floorplan should be automatic display of selected project in another dropdown, and I am using ForeignKey relation with projectfloorplan in Property model, but it's displaying all projects floorplan list in the dropdown, Please let me know how I can display particular projectfloorplan in Dropdown if I select any Project. here is my models.py file for the Property model... class Property(models.Model): project=models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_listing') floorplan=models.ForeignKey(ProjectFloorPlan, on_delete=models.CASCADE, related_name='project_floorplan') -
Access a pdf file from views.py which is created by Js in a Django project
I am trying to render with HTML to pdf in my Django project. I am using html2pdf package form js and render my html into pdf by following link: youtubelink. my template: <div class="container-fluid py-5 bg-light"> <div class="col-xl-10 bg-white" id="pdf_portion"> <p>Lots of staff is in this div. I just skip those unnecessary things in this question.</p> </div> </div> <button class="btn btn-primary" id="download"> download pdf</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js"></script> <script type="text/javascript"> window.onload = function () { document.getElementById("download") .addEventListener("click", () => { const invoice = this.document.getElementById("pdf_portion"); console.log(invoice); console.log(window); var opt = { margin: 0.8, filename: 'myfile.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 4 }, jsPDF: { unit: 'in', format: 'A4', orientation: 'portrait' } }; html2pdf().from(invoice).set(opt).save(); }) } </script> Here the 'download' button gives us the option to download the pdf. I need to send the pdf in my views.py in any method, thus I will able to save it in my database's filefield. Please suggest How can I able to access that pdf file in my views.py. -
Page not found, dynamic URLs | Django
I'm having some trouble on performing a query in Django 3.1.4. The main problem is that the field that I use for my dynamic URLs can sometimes be a string with slashes: 'ABC/1/2/3D' This last one I'm having trouble with due to the slashes Rather than creating a slug field in the model and just replacing those slashes with some value (an _ per say) and using that parameter, I'd like to pass the parameter with the _ (without existing in my model) in the URL and then, replace all the _ with / to perform the query. views.py class DetailViewTest(LoginRequiredMixin, PermissionRequiredMixin, DetailView): slug_field = "some_stuff" slug_url_kwarg = "some_stuff" model = Stuff template_name = 'things/stuff.html' permission_required = 'stuff.view_stuff' def get_context_data(self, *args, **kwargs): context = super(DetailViewTest, self).get_context_data(**kwargs) if self.kwargs['some_stuff'].find('_') == -1: stuff = get_object_or_404(Stuff, some_stuff=self.kwargs['some_stuff']) # This is were I'm having some trouble else: temp_stuff = self.kwargs['some_stuff'].replace('_', '/') stuff = get_object_or_404(Stuff, some_stuff=temp_stuff) thing = stuff # Some other code goes here... context['...'] = ... return context urls.py urlpatterns = [ path('<str:some_stuff>/test/', DetailViewTest.as_view(), name='stuff_test'), ] As you can see, 'some_stuff' is the parameter I use, I works fine with values that don't have slashes However, when I pass 'TEST_12' for example, it … -
Am using drf-spectacular for my Django rest api documentation am getting below error when i am trying to over SPECTACULAR_SETTINGS in setting.py
Settings are configurable in settings.py in the scope SPECTACULAR_SETTINGS. You can override any setting, otherwise the defaults below are used. for ref: https://drf-spectacular.readthedocs.io/en/latest/settings.html [ -
How to request data as json response in Django?
How can i make request as a jsonResponse with template rendering also? The code below is working fine but i want to convert data as json data and i want to get data with ajax request jquery in template. I would be grateful for any help. VIEWS.py def Prompter(request, pk): obj = get_object_or_404(SetRundown, pk=pk) articles = obj.articles.order_by('position') return render(request, 'prompter.html', {'articles': articles}) -
An object is returning true even if it is not there
So i'm trying to see if the user has something in their cart, if they don't and they click on chekout then it should say that their cart is empty but it just makes an order object. makeorder and createorder function handles creating orders. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) … -
EmptyPage at /HomeFeed/ That page contains no results
This is a very weird Django Pagination problem: My django project is basically a blog website where people can make posts. So here I'm trying to query blog posts that belong to a user and page them. Basically, if the logged in user hasn't made any posts or that he has made enough posts to go beyond one page, everything works and this error does not shot. This error only shows when the logged in user has less than the number of posts a page should have. Why is this so? In case you are wondering why I am using page2 in my template instead of page, its because I have another pagination on the same page, so it's used to differentiate them... Error points to this line: blog_post = own_account_post.page(page) and also says that During handling of the above exception (int() argument must be a string, a bytes-like object or a number, not 'NoneType'), another exception occurred: in my browser. views.py def home_feed_view(request, *args, **kwargs): context = {} if request.user.is_authenticated: if BlogPost.objects.filter(author=request.user.id).exists(): blog_post = BlogPost.objects.filter(author=request.user.id).order_by('date_updated') page = request.GET.get('page2') own_account_post = Paginator(blog_post, 3) try: blog_post = own_account_post.page(page) except PageNotAnInteger: blog_post = own_account_post.page(3) except EmptyPage: blog_post = own_account_post.page(blog_post_paginator.num_pages) context['blog_post'] = blog_post … -
Django async view giving the same result as sync view
I am learining async views and just at the beginning i encountered a problem. Async view should run two functions at the same time but they go one after another just like in the regular view. What am I doing wrong? # helper funcs def get_movies(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print(qs) print('got all the movies.') def get_stories(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print(qs) print('got all the stories.') @sync_to_async def get_movies_async(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print(qs) print('got all the movies.') @sync_to_async def get_stories_async(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print(qs) print('got all the stories.') def main_view(request): start_time = time.time() get_movies() get_stories() total = (time.time() - start_time) print('Total: ', total) return HttpResponse('sync') async def main_view_async(request): start_time = time.time() # task1 = asyncio.ensure_future((get_movies_async())) # task2 = asyncio.ensure_future((get_stories_async())) # await asyncio.wait([task1, task2]) await asyncio.gather(get_movies_async(), get_stories_async()) total = (time.time() - start_time) print('Total: ', total) return HttpResponse('async') -
Error passing field to views, How do I correctly pass the model field to the view?
I am trying to pass a model field to the view to calculate the sum of time, but I get an error: Cannot resolve keyword 'hours_worked' into field. Choices are: car, car_id, date, deal_gts, deal_me, driver, driver_id, finish_work, gain, id, start_work models.py class Trip(models.Model): date = models.DateField(auto_now=False, verbose_name='Дата') car = models.ForeignKey(Cars, on_delete=models.CASCADE, verbose_name='Автомобиль') driver = models.ForeignKey(Driver, on_delete=models.CASCADE, verbose_name='Водитель') start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(max_length=20, blank=True, verbose_name='Отработано часов') deal_me = models.IntegerField(verbose_name='Сделки МЭ', blank=True, default=0) deal_gts = models.IntegerField(verbose_name='Сделки ГТС', blank=True, default=0) gain = models.IntegerField(verbose_name='Выручка') class Meta: verbose_name = 'Доставка' verbose_name_plural = 'Достваки' def hours_worked(self): fw = self.finish_work sw = self.start_work hw = datetime.combine(date.today(), fw) - datetime.combine(date.today(), sw) hours_worked = str(hw).rsplit(':', 1)[0] return hours_worked wiews.py from django.shortcuts import render, redirect from .forms import TripForm from .models import Trip def home_view(request): trip = Trip.objects.all() # сумма чвасов sum_hour = 0 me = Trip.objects.values_list('hours_worked') # print(me) for el in me: for i in el: sum_hour = int(sum_hour) + int(i) context = { 'sum_hour': sum_hour } return render(request, 'driver_productivity/home.html', context) Tell me if I'm thinking in the right direction, or is it better to do the calculation not in the model? -
How to select from a subquery in Django's ORM?
I want to select all rows for which bet_index is not NULL: BetHistory.objects.values('account_id').annotate( bet_index=models.Case(models.When( models.Q(event_id=1, market_id=2) & (models.Q(account_id=3) | models.Q(account_id=4)), then=0), default=None, output_field=models.IntegerField()) ).exclude(bet_index=None) that yields the following SQL query SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history" WHERE NOT ( CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end IS NULL ) but there the case is repeated, I would like to have the following query: SELECT * FROM (SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history") AS "subquery" WHERE "subquery"."bet_index" IS NOT NULL; so I need a select from subquery, how to do it in Django? Thanks. -
Celery tasks don't run in docker container
In Django, I want to perform a Celery task (let's say add 2 numbers) when a user uploads a new file in /media. What I've done is to use signals so when the associated Upload object is saved the celery task will be fired. Here's my code and Docker configuration: signals.py from django.db.models.signals import post_save from django.dispatch import receiver from core.models import Upload from core.tasks import add_me def upload_save(sender, instance, signal, *args, **kwargs): print("IN UPLOAD SIGNAL") # <----- LOGS PRINT UP TO HERE, IN CONTAINERS add_me.delay(10) post_save.connect(upload_save, sender=Upload) # My post save signal tasks.py from celery import shared_task @shared_task(ignore_result=True, max_retries=3) def add_me(upload_id): print('In celery') # <----- This is not printed when in Docker! return upload_id + 20 views.py class UploadView(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = UploadSerializer def post(self, request, *args, **kwargs): serializer = UploadSerializer(data=request.data) print("SECOND AFTER") print(request.data) <------ I can see my file name here if serializer.is_valid(): print("THIRD AFTER") <------ This is printer OK in all cases serializer.save() print("FOURTH AFTER") <----- But this is not printed when in Docker! return response.Response( {"Message": "Your file was uploaded"}, status=status.HTTP_201_CREATED, ) return response.Response( {"Message": "Failure", "Errors": serializer.errors}, status=status.HTTP_403_FORBIDDEN, ) docker-compose.yml version: "3.8" services: db: # build: ./database_docker/ image: postgres ports: - "5432:5432" environment: POSTGRES_DB: test_db … -
duplicate key value violates unique constraint "usuarios_usuario_email_key" DETAIL: Key (email)=() already exists
I'm looking for users in an old model and saving in a new model, only that my new model the email is unique, I would like to know how I can do a check if there is an equal email, do not save this email and leave it blank @task(bind=True) @transaction.atomic def importa_usuario(self, id_usuarios=None): logger.info('Importando V2: %s', self.name) lock_id = '{0}-lock'.format(self.name) antes = datetime.datetime.utcnow().replace(tzinfo=timezone.utc) - datetime.timedelta(hours=2) agora = datetime.datetime.utcnow().replace(tzinfo=timezone.utc).time() with memcache_lock(lock_id, self.app.oid) as acquired: if settings.DEBUG: import pdb; pdb.set_trace() acquired = True if acquired: logger.info("Buscando usuario...\r") usuarios = list(Usuarios.objects.all().order_by('-id')[:100]) logger.info("{0} Amostra liga encontrada".format(len(usuarios))) dados_webmap = { "usuarios": usuarios } logger.info('Importando dados...') count = 0 erro = 0 total = len(usuarios) logger.info("Excluindo dados anteriores...\r") if id_usuarios: usuarios = list(filter(lambda lista: lista.id == int(id_usuarios), usuarios)) for usuario in usuarios: logger.info("Importando {0} dados...\r".format(len(usuarios))) usuario_atual = Usuario.objects.filter(id=int(usuario.id)) if usuario_atual.exists(): usuario_atual.delete() dado = Usuario() try: dado.id = usuario.id dado.email = usuario.email dado.first_name = usuario.nome dado.set_password("senha") dado.save() enter image description here -
how can I grab a number from URL and check it's length in django?
I need to verify the length of number grabbed from URL such as example.com/12345678 in django ? urlpatterns = [ path("", main.views.index, name="index"), path("admin/", admin.site.urls), path('<int:tnum>/', main.views.number, name="number") And if the number doesn't match a certain length I want to output number is invalid. -
Why am I getting a network error when trying to make an axios post request from a react-native app to my django server?
I am trying to set up a login service for my react-native app. When trying to send an axios post request to my django server i get a network error. The django server shows that it has received a request but gives it error 400. I have added CORS to the django server and the requests work fine using Postman. I have been following this tutorial on how to set it up: https://towardsdatascience.com/build-a-fully-production-ready-machine-learning-app-with-python-django-react-and-docker-c4d938c251e5 Please could somebody tell me what I've done wrong. Here is my code: settings.py (snippet) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'corsheaders', 'prediction', 'users', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mainapp.urls' CORS_ALLOW_ALL_ORIGINS = True actions.py export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post(`http://localhost:8000/api/auth/login/`, { username: username, password: password, }) .then(res => { const token = res.data.key; const expirationDate = new Date(new Date().getTime() + SESSION_DURATION ); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(authCheckTimeout(SESSION_DURATION)); }) .catch(err => { console.log(err) dispatch(authFail(err)) }); } } I can provide any other parts of my code if required. -
Django, Path return 404
I've got an issue with my Django app, when i try to browse to http://127.0.0.1:8000/list/ it returns a 404 error : Using the URLconf defined in f_django.urls, Django tried these URL patterns, in this order: ^contact/$ ^description/$ ^$ myapp/ admin/ The current path, list/, didn't match any of these. Here my urls.py file : from django.contrib import admin from django.urls import path from django.conf.urls import url from django.urls import include from . import views urlpatterns = [ url(r'^contact/$',views.contact), url(r'^description/$',views.description), url(r'^$',include('myapp.urls')), path('myapp/',include('myapp.urls')), path('admin/', admin.site.urls), ] My myapp/urls.py file : from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^$',views.index), url(r'^list',views.list), url(r'^Articles/(?P<id>[0-9]+)$', views.details), ] And this line in my settings.py : INSTALLED_APPS = [ 'myapp.apps.MyappConfig', ] Thanks in advance for your help -
Simple to do app but with different tasks in a each group(many to one relationship)
Main problem: When user is at this url http://127.0.0.1:8000/8/, so group_id is already in url of his current page, he must choose group_id that he wants to assign task, if I do fields = ['title', completed'] in forms.py user can't choose group_id but he needs to. I have primary key but I don't know where to apply it in views P.S.: IndexView from views.py has no problem in it and works fine, also get method in GroupView works fine to. Anything works fine but user needs to choose a group that he want's to assign tasks forms.py: from django import forms from .models import * class AddTaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' class AddGroupForm(forms.ModelForm): class Meta: model = Group fields = '__all__' models.py from django.db import models from django.utils import timezone class Group(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title class Task(models.Model): title = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return self.title def task_is_expired(): return timezone.now() < self.deadline views.py from django.shortcuts import render, redirect from django.views import generic from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .models import * from .forms import * class IndexView(generic.ListView): template_name = 'tasks/index.html' form_class = AddGroupForm … -
Send_mail() triggered at the same time by different users
Say that I have 10 different users that register at the same time and system is sending email to every registered user. I am wondering what would the process look like when Django send_mail() is triggered multiple times simultaneously - do those emails queue and are executed one by one and simply slower the registration process for some users and making them wait till their emails are sent (so they wait little longer to be redirected after hitting 'Register' button)? Or would that end up with some sort of error? I know that I could use Celery and make it asynchronous, but I am curious what happens without it and if the only problem that I should be concern of is website working slower in such case.