Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to filter data before exporting to csv
I'm very beginner in django. Now I'm working on my first very simple application. I have a working filter: def filter_view(request): qs = My_Model.objects.all() index_contact_contains_query = request.GET.get('index_contact_contains') nr_order_contains_query = request.GET.get('nr_order_contains') user_contains_query = request.GET.get('user_contains') date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(index_contact_contains_query): qs = qs.filter(index_contact__icontains = index_contact_contains_query) elif is_valid_queryparam(nr_order_contains_query): qs = qs.filter(nr_order__icontains = nr_order_contains_query) elif is_valid_queryparam(user_contains_query): qs = qs.filter(nr_user = user_contains_query) if is_valid_queryparam(date_min): qs = qs.filter(add_date__gte = date_min) if is_valid_queryparam(date_max): qs = qs.filter(add_date__lt = date_max) if export == 'on': ?????????????? - export file context = { 'queryset':qs } return render(request,'filter.html',context) I have also working function for export data to csv file: def download_csv(request): items = My_Model.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' writer = csv.writer(response) writer.writerow(['index_contact','nr_order','result','nr_user','tools','add_date']) for obj in data: writer.writerow([obj.index_contact, obj.nr_order, obj.result, obj.nr_user, obj.tools, obj.add_date]) return response My question is... how to connect both functions and export csv file with filtered data. I also have a request... Please give me a hint as for a beginner Thanks for any suggestions -
Django / Crispy Forms: Display first_name instead of username in renderd form
I have a model which uses the User model as ForeignKey. Then I render the form with crispy forms the usernames are shown for the shared_with select box. How can I change this to user.firstname instead of user.names? Do I have to change the queryset of this field? models.py class box_items(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='OwnerToUser') shared_with = models.ForeignKey(User, on_delete=models.PROTECT, related_name='SharedToUser',null=False) tags = models.ManyToManyField(box_tags, blank=True) name = models.CharField(max_length=140, blank=False) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms.py class item_form(forms.ModelForm): tags = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(),required=False,queryset=box_tags.objects.order_by('name')) def __init__(self, *args, **kwargs): self.user = kwargs.pop('current_user', None) #ERROR HANDLING!!! super(item_form, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.layout = Layout( Submit('submit', 'Speichern'), CustomTags('tags'), 'shared_with', 'name', 'description', Submit('submit', 'Speichern') ) -
Exception in thread django-main-thread: Traceback (most recent call last): NameError: name 'articles' is not defined
https://imgur.com/a/XKbG8y5 --- image, please look! I can not runserver in django (I need help!) -
Django doesn't work on AWS elastic Beanstalk
I have deployed a Django APP in AWS Elastic Beanstalk. Sometimes it works but after some requests it stops to work and reading the logs it returns: [Thu Feb 27 21:59:12.073643 2020] [mpm_prefork:notice] [pid 3195] AH00169: caught SIGTERM, shutting down [Thu Feb 27 21:59:13.429395 2020] [suexec:notice] [pid 3568] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Thu Feb 27 21:59:13.495004 2020] [so:warn] [pid 3568] AH01574: module wsgi_module is already loaded, skipping [Thu Feb 27 21:59:13.534589 2020] [http2:warn] [pid 3568] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Thu Feb 27 21:59:13.534607 2020] [http2:warn] [pid 3568] AH02951: mod_ssl does not seem to be enabled [Thu Feb 27 21:59:13.535166 2020] [lbmethod_heartbeat:notice] [pid 3568] AH02282: No slotmem from mod_heartmonitor [Thu Feb 27 21:59:13.535239 2020] [:warn] [pid 3568] mod_wsgi: Compiled for Python/3.6.2. [Thu Feb 27 21:59:13.535252 2020] [:warn] [pid 3568] mod_wsgi: Runtime using Python/3.6.8. [Thu Feb 27 21:59:13.539566 2020] [mpm_prefork:notice] [pid 3568] AH00163: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 configured -- resuming … -
How to deploy a Django App + Swagger UI in Heroku
I have a running backend API in Django deployed in Heroku. I want to add documentation to my endpoints using Swagger Ui but I want to do this manually, not with the libraries like drf-yasg. How do I do this? -
How do I call Django function on button click
I am working on a dating website and I am confuse on how to replace button on click. For example if a user(John) send a friend request to another user(Paul), how can I replace the button in Paul's profile from 'add friend' to 'accept request'. Then if no user send a friend request to Paul the button will return to default 'add friend'. -
How can I use a pop up instead of a page redirection for a view using django?
I'm working on a "watchlist" app and right now, when I remove an element from it, it redirect me to another page, altought I would simply like to have a pop up coming up after the action saying "removed", I have a hard time figuring how to do it as I'm using {% url %} wich included the key.id that has been selected to add or remove. watchlist.html <td>{{key.symbol}}</td> <td>{{key.company_name}}</td> <td>{{key.change_percent}}</td> <td>{{key.sector}}</td> <td>{{key.date}}</td> <td><a href="{% url 'watchlist:delete' key.id %}">Delete from watchlist</a></td> views.py def delete_from_watchlist(request, pk): item_deleted = Stock.objects.get(id=pk) symbol = item_deleted.symbol stock_deleted = Watchlist_item.objects.get(tag=symbol) t = stock_deleted.tag t = str(t) stock_deleted.delete() my_dict = {"title":'watch_delete',"stock_deleted":"You have succesfully deleted " + t + " from your watchlist"} return render(request, 'watchlist/watch_item_deleted.html',context=my_dict) Simple pop-up script <button onclick="myFunction()">Remove from watchlist</button> <script> function myFunction() { alert("This stock has been removed of your watchlist"); } </script> urls.py urlpatterns =[ path('', views.watchlist, name="watchlist_list"), path('add/<int:pk>/', views.add_to_watchlist, name="add"), path('watchlist/delete/<int:pk>/', views.delete_from_watchlist, name="delete"), ] If there is anything missing ask me and I shall try to provide all answers needed for you to help me ! Thanks for your help everyone ! -
NoReverseMatch dispite following examples
I am fairly new to Django - Having followed many examples and tutorials online - I have produced my various models over some time. I have run into an error: NoReverseMatch at /Organisation/organisations Reverse for 'Organisation' not found. 'Organisation' is not a valid view function or pattern name.' Request Method: GET Request URL: http://127.0.0.1:8000/Organisation/organisations Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'Organisation' not found. 'Organisation' is not a valid view function or pattern name. The details for the code I'm using is as follows: def get_absolute_url(self): #Returns the url to access a detail record for organisation. return reverse('Organisation', kwargs= {'pk':self.pk}). My Relevant Model - Form_Field_OrgID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Form_Field_OrgName = models.CharField(max_length=100, help_text='Enter Organisation Name', verbose_name = "Organisation Name") Form_Field_OrgAddr = models.CharField(max_length=50, help_text='Enter Organisation Address', verbose_name = "Organisation Address") Form_Field_OrgAddr2 = models.CharField(max_length=50, help_text='Enter Organisation Address', verbose_name = "Organisation Address") Form_Field_OrgAddr3 = models.CharField(max_length=50, help_text='Enter Organisation Address', verbose_name = "Organisation Address") Form_Field_OrgAddr4 = models.CharField(max_length=50, help_text='Enter Organisation Address', verbose_name = "Organisation Address") Form_Field_OrgCountry = models.CharField(max_length=250, help_text='Select Organisation Country', verbose_name = "Organisation Country") Form_Field_OrgPcode = models.CharField(max_length=10, help_text='Enter Organisation Post Code', verbose_name = "Organisation Address") Form_Field_OrgEmail = models.EmailField(max_length=254, help_text='Enter Organisation Email', verbose_name = "Organisation Email Address") Form_Field_OrgPhone = models.CharField(max_length=12, help_text='Enter Organisation Phone … -
Django Rest Framework, passing a parameter with url to ModelViewSet
I want to pass a parameter in the url and use it to filter the objects. My view so far looks like this. class RecipeIngredientViewSet(viewsets.ModelViewSet): queryset = RecipeIngredient.objects.all() serializer_class = RecipeIngredientSerializer I would like to get all the ingredients related to one recipe. Like this: queryset = RecipeIngredient.objects.filter(recipe_id=id) When I hardcode recipe_id=1 it's working. Thats the line in url: router.register(r'recipe/', views.RecipeIngredientViewSet) Tried different approaches and failed so far. I'll be glad for any help. -
Table doesn't exist error in Django when using two databases
I have a Django project where i'm using two Databases. On a view, i have the following query: data = get_object_or_404(MyModel, ticker=ticker).using('second') This query will raise the following error: (1146, "Table 'db.myapp_mymodel' doesn't exist") Which happens because Django is looking for the table in the first database, while the table is in the second database. Why does this happen even when i used using() and when in my model it's specified that the table is located on my second database? How can i fix this? Thanks in advance! -
Django model validation on blank values
If you define a field with blank=True then validation properly allows blank values and if blank=False then blank values raise a validation exception. Usually it's pretty simple, but with JSONField it's possible to have one of 3 different blank values which are: '', [], {}. Essentially, I'd like to only allow {} as the only acceptable blank value. However, blank values are never passed to custom field validators so it seems like it's not possible through standard means. def validate_dict(value): if not isinstance(value, dict): raise ValidationError( '"%(value)s" is not valid JSON', params={'value': value}, ) class MyModel(models.Model): json = JSONField(default=dict, blank=True, validators=[validate_dict]) In the above example, all the "blank" values are immediately seen as valid and validate_dict is never called. If I change blank=True to blank=False then all blank values are immediately seen as invalid and again validate_dict is never called. I'd like to validate that the stored data is always a dict, but it seems to be impossible to validate that the empty value is a dict only. -
Django Saleor legal issue with license
I am not getting where to post this question. I have a client with a huge budget for e-commerce website. I decided i will develop ecommerce site with saleor https://github.com/mirumee/saleor and their website says it is opensource. I am not getting if I build eCommerce site with saleor for my client, will saleor take ligal acction againist me or my client? coz, it is developed by salor and we are using this for free. I am not getting should i go with saleor or should I develop from scratch. Can anyone please explain this? I have read their licens and the licen are not clear to me what they mean. -
How to pass queryset as single items inDdjango?
I have the following in my views.py: Going = Flight.objects.filter(date__gt=datetime.now()).order_by('-date') This fetches all flights leaving after now. But, when I pass it to the template through {{Going}}, I get the queryset <QuerySet [<Flight: TP450>]> instead of the each single flight. In my model, each flight has a flight_ref. How can I pass each item so I can create a table with them? -
Django - Add external database via user interface to make query
I'm writing a Web Application with Django. My main read/write db is the default sqllite For one of my app, i'm trying to connect two external Oracle DataBase (read-only) (2 for now but this will grow with time). So i would like to be able to add the connection to all the database via the Web application GUI. For those external database i will only do SQL query (no edit, no delete, ...) I think the way to go would be to create a "DB_CREDENTIAL" Table in the default DB DB_CREDENTIAL - NAME - ENGINE - USER - PASSWORD But from there i don't exactly know where to go Am i doomed to add them in the setting.py ? If so is there anyway to modify it in the GUI of the WebApp ? Or maybe there other way to query those database that are simpler ? -
Angular 8 - problem with GET request for a json file
Please help, i'm trying to lift up my django web page with REST API and use Angular FrontEnd where I am beginning. I have followed some tutorials on how to consume REST api and somehow I'm making a mistake there. The browser shows no errors when requesting the content but it is not coming. I appreciate every bit of help..... here we go usluga-list.component.ts: import { Component, OnInit } from '@angular/core'; import { Observable } from "rxjs"; import { Usluga } from "../models/usluga"; import { UslugaService } from "../services/usluga.service"; @Component({ selector: 'app-usluga-list', templateUrl: './usluga-list.component.html', styleUrls: ['./usluga-list.component.css'] }) export class UslugaListComponent implements OnInit { uslugi: Observable<Usluga[]>; constructor(private uslugaService: UslugaService) { } ngOnInit() { this.loadUslugiData(); } loadUslugiData(){ this.uslugi = this.uslugaService.getAllUslugi(); then i have usluga.service.ts: import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { Usluga } from "../models/usluga"; @Injectable({ providedIn: 'root' }) export class UslugaService { private endpoint ='http://localhost:8000/uslugi/'; constructor(private http: HttpClient) { } getAllUslugi(): Observable<any>{ return this.http.get(this.endpoint) } getUsluga(id: number): Observable<any> { return this.http.get(this.endpoint + id); } } Then I have app-routing.ts: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UslugaListComponent } from './usluga-list/usluga-list.component'; … -
Reverse for 'anhangdelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P<id>[0-9]+)$']
Error: Request Method: GET Request URL: http://127.0.0.1:8000/Verwaltung/Anhang/10 Django Version: 3.0.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'anhangdelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P[0-9]+)$'] Exception Location: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\Scripts\python.exe Python Version: 3.8.0 views.py @login_required() def anhang_view(request, id=None): contextoo = {} item = Kunden.objects.get(id=id) kontaktform_form = KontaktForm(request.POST or None, instance=item) creatorform_form = CreateANform() contextoo['creatorform_form'] = creatorform_form if Kunden.objects.filter(KN=item.KN).exists(): item14 = Kunden.objects.get(KN=item.KN) editkontakto_form = InfoKontaktoForm(request.POST or None, instance=item14) contextoo['editkontakto_form'] = editkontakto_form if Anhang.objects.filter(KN=item.KN).exists(): item15 = Anhang.objects.filter(KN=item.KN) contextoo['ANform_form'] = item15 if request.method == 'POST': creatorform_form = CreateANform(request.POST) if creatorform_form.is_valid(): cre = creatorform_form.save(commit=True) cre.save() return redirect('/Verwaltung/KontaktAnlegen') else: return render(request, 'blog/anhang.html', contextoo) @login_required() def AnhangDeleteView(request, id): anh = Anhang.objects.get(id=id) anh.delete() return redirect(reverse('blog:Anhang')) urls.py path('AnhangDelete/<int:id>', views.AnhangDeleteView, name='anhangdelete'), anhang.html . . . {% if ANform_form %} {% for obj in ANform_form %} <table class="table" width="100%" border="0" cellspacing="0" cellpadding="0"> <thead class="thead-light"> <tr> <td width="11%" border="0" cellspacing="0" cellpadding="0"> <b> {% csrf_token %} {{ obj.Thema }} </b> </td> <td width="15%" border="0" cellspacing="0" cellpadding="0">Username</td> <td width="19%" border="0" cellspacing="0" cellpadding="0">Password</td> <td width="18%" border="0" cellspacing="0" cellpadding="0">E-Mail</td> <td width="37%" border="0" cellspacing="0" cellpadding="0">Anhang</td> <td> </td> <td></td> </tr> </thead> <tbody> <td></td> <td> {% csrf_token %} {{ obj.Username }} </td> <td> {% csrf_token %} {{ obj.Password }} </td> <td> … -
Django edits rows instead of adding a new one
Is there any reason why code like this would edit the only row from a table instead of creating a new one? newStudent = Student(name=var.name, mark=var.mark, year=newyear) newStudent.save() Explanation: I am working on student records. This view is called when I'm updating a student's information. var.name is the student's name before the edit and var.mark is his mark before the edit. newyear is the year I'm adding this information for. This view is called every year (i.e. a student has a new name and mark every year). After these lines, I proceed to edit the student's current year information. The problem: This code edits the only row from the Student table in the database instead of adding a new one. -
Django run tasks (possibly) in the far future
Suppose I have a model Event. I want to send a notification (email, push, whatever) to all invited users once the event has elapsed. Something along the lines of: class Event(models.Model): start = models.DateTimeField(...) end = models.DateTimeField(...) invited = models.ManyToManyField(model=User) def onEventElapsed(self): for user in self.invited: my_notification_backend.sendMessage(target=user, message="Event has elapsed") Now, of course, the crucial part is to invoke onEventElapsed whenever timezone.now() >= event.end. Keep in mind, end could be months away from the current date. I have thought about two basic ways of doing this: Use a periodic cron job (say, every five minutes or so) which checks if any events have elapsed within the last five minutes and executes my method. Use celery and schedule onEventElapsed using the eta parameter to be run in the future (within the models save method). Considering option 1, a potential solution could be django-celery-beat. However, it seems a bit odd to run a task at a fixed interval for sending notifications. In addition I came up with a (potential) issue that would (probably) result in a not-so elegant solution: Check every five minutes for events that have elapsed in the previous five minutes? seems shaky, maybe some events are missed (or others … -
Django how to compute the Percentage using annotate?
I want to compute the total average per grading categories and multiply it by given number using annotate this is my views.py from django.db.models import F gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\ (Grading_Categories__in = cate.values_list('id')).values('Grading_Categories').annotate( average_grade = Avg * F('Grading_Categories__PercentageWeight') / 100) this is my models.py class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() class studentsEnrolledSubjectsGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) -
Web development using python
Just asking that what are the other libraries that should be known by a person for the full web development with the help of python currently i know pandas,numpy ,matlab ,matplot lib,django -
APScheduler Quits at Network Call
Im using a BlockingScheduler, and my function is invoked at the intended interval, but the whole function doesn't run, only the first line does. @register_job('interval', minutes=1) def run_content_cron(): send_sms('+5555555555', 'inside clock.py content') # this runs <database call> # function quits here--this never runs -
How to fix TypeError: 'module' object is not callable in python using BytesIO
I face the problem of TypeError: 'module' object is not callable. My aim is to use BytesIO to print in pdf. The code that seems to have the error is : def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = context_dict html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), dest=result, encoding="utf-8", ) And my Traceback indicating the error is : Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/vhosts/intranet.rodkok.gr/apografi_new/intranet/views.py" in pdf_clients_analysis 1766. 'clients':clients File "/var/www/vhosts/intranet.rodkok.gr/apografi_new/intranet/views.py" in render_to_pdf 2176. result = BytesIO() Exception Type: TypeError at /pdf_analysis/2020-01-012020-02-27/ Exception Value: 'module' object is not callable It seems that the problem does not have to do with the type of the content(String or Byte) Any idea how to fix it? -
Reset Password Form Page not found
I have built a custom password reset from in Django, However after putting the information in password reset form I get a 4040 page not found error This is my view for reset_password def reset_password(request,username): if request.method == 'POST': form = PasswordResetForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) #added this to redirect user to custom url username = request.user.username return redirect(reverse('main:home', kwargs={'username': username})) #return redirect(reverse('main:home')) else: return redirect(reverse('main:reset_password')) else: form = PasswordResetForm(user=request.user) args = {'form': form} return render(request, 'reset_password.html', args) My urls at myapp/urls.py urlpatterns=[ path('signup/',views.signup,name='signup'), path('login',views.user_login,name='user_login'), path('',views.main_page,name='main_page'), path('<str:username>', views.home, name='home'), #replace home/edit with below path('<str:username>/edit', views.edit_profile, name='edit_profile'), path('<str:username>/password-reset', views.reset_password, name='reset_password'), ] and my form for password reset: class PasswordResetForm(PasswordChangeForm): class Meta: model = Profile fields = ('old_password','new_password1','new_password2') What seems to be the problem here? I do not know why I am getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/main/test3-b/login.html?next=/main/test3-b/password-reset This is my AbstractUser model in models.py (I do not have any other code in my models.py class Profile(AbstractUser): bio = models.TextField() university = models.CharField(max_length=30) def __str__(self): return self.username -
Images not appearing in saleor base.html
I am using divio to run my saleor server. I added files to my static assets image folder. When I add the image to my base html it doesn't appear. I have placed the images inside the /saleor/static/images folder and then ran the command docker-compose run --rm web npm run build-assets --production. However, my images still aren't appearing, what am I missing? -
Select intersected geometries between two tables in GeoDjango
I have two models A and B. Help please with the help of ORM to query A records that intersects with B records with geometry field: Model A: class ModelA(models.Model): id = models.IntegerField(primary_key=True) properties = JSONField() geometry = models.MultiPolygonField() Model B: class ModelB(models.Model): id = models.IntegerField(primary_key=True) properties = JSONField() geometry = models.GeometryField() // can be any valid geometry: Point, Polygon, MultiPolygon