Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding arguments to Django include('django.contrib.auth.urls')
I am trying to add an additional argument to my Django default password reset which is mysite.com/password_reset. I am trying to make it look like: mysite.com/user/password_reset.Right now I am using this method: Code for home.html(Contains password change link) <li><a href="{% url 'password_reset' user.username %}">Change Password</a></li> My app/urls.py: path('<str:username>/', include('django.contrib.auth.urls')), This is the Error I am getting: NoReverseMatch at /test3-b Reverse for 'password_reset' with arguments '('test3-b',)' not found. 1 pattern(s) tried: ['password_reset/$'] Thanks in advanc! -
Many to Many relationships in template
Good day guys, im new to django im having in many to many relationship display in template How can display this into a normal list.. from . QuerySet User: webadmin, User: kim, User: sem, User: quinito, User: user1 to. webadmin kim sem quinito user1 Here's my code model.py class ListOfUser(models.Model): users = models.ManyToManyField(User, verbose_name='List of User') views.py def listofusers(request): userlist = ListOfUser.objects.get(id=1) form = ListofUserForms() context = { 'form': form, 'userlist': userlist } return render(request, 'listofusers.html', context) template <p>{{userlist.users.all}}<p> -
django - how to download uploaded files ..not able to download on localhost
Hello I am trying to download a files that I uploaded in my django project. In the List of files available for download, I am storing the url column as a FeildFile object as follows: `>>> File.objects.all() <QuerySet [<File: bvbv>, <File: test-shsh>, <File: gsdsgdsg>, <File: vbvbv>, <File: bnbn>]> >>> file = File.objects.all()[0] >>> file <File: bvbv> >>> file.url <FieldFile: files/contents/test.docx> >>> ` When I construct the links in my view I get then of the form http://localhost:8000/files/files/contents/test.docx instead of http://localhost:8000/media/files/contents/test.docx This is not allowing me to download the files. Any clews Here is my code snippet: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CRISPY_TEMPLATE_PACK = 'bootstrap4' MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.Home.as_view(), name='home'), path('upload/', views.upload, name='upload'), path('files/', views.file_list, name='file_list'), path('file/upload/', views.upload_file, name='upload_file'), path('files/<int:pk>/', views.delete_file, name='delete_file'), if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) file_list.html <td>{{ file.url }}</td> <td> <a href="{{ file.url }}" class="btn btn-primary btn-sm" target="_blank"> Download File </a> </td> -
Is it possible to use objects created in other forms in Django?
I have a form to create a trip. In this form, you have to choose a client, outbound_flight, inbound_flight and a hotel. Is it to possible to let the user, who is using the trip form, create any of those objects in another form respective to each model, and then automatically bring the object created to the trip form? -
Using Django REST and React Frontend with an external SQL DB. On form submit, need to populate API and also push same data to a stored proc
First up, I know I'm going about this the wrong way, but the SQL database is an existing project so I have to use that right now, and I'm just building this API and Frontend around it as a way to convince the higher ups to get us proper training. Ideally I'd do this from scratch in Django, but I don't have a choice right now. So, where I'm at right now is I have the SQL DB listed in the django settings, and that's all fine. I have some (enough for testing) of the form built, and the data from the form will populate the API: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() Somewhere along the line (I'm learning as I go (badly)) I found a way to intercept the form data on submit, and call my stored proc. I've absolutely zero doubt there's a better way to do this, but here we are: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() def dispatch(self, request, *args, **kwargs): if request.method == 'POST': body = json.loads(request.body) title = body['title'] desc = body['description'] owner = body['owner_lan'] sme = body['sme_lan'] etc **stored proc stuff** return super(TodoView, self).dispatch(request, *args, **kwargs) else: return super(TodoView, … -
Django If statement with boolean fields not working
I'm getting the boolean value from a queryset like this: activo = Carros.objects.all().values_list('is_active', flat=True).filter(nombre='carro') then my if statement is this: if activo == True: raise forms.ValidationError('El Auto está activo') even though the variable 'activo' gets a True value it does not return the ValidationError. What I did was to set a variable a = True and then add it in the if statement if activo == True: raise forms.ValidationError('El Auto está activo') And it works. In the Python shell whenver I excute the query I see the result lik this <QuerySet [True]> I'm not sure what is the problem. the 'is_active' field in the model: is_active = models.BooleanField(blank=False, null=False, default=True) Note: DB is Postgresql -
Django FileField upload link for detailview?
My 2nd question of the day, loosely related to the first (trying to accomplish same thing in different ways), so bear with me as I learn stuff! lol My Django app allows me to upload a a FIT file, which is cycling data that contains several thousand rows of data in a ride file. What I'm hoping to accomplish is opening a detailview in which the file is analyzed with graphs and metrics (that's the easy part!). Is there a way to call on the object's url in the detailview class? In the snipped below, I have the detailview class, the model is just comprised of the FileField object and then the last portion is code which I use to parse this type of file. I've done a lot of searching and I haven't seen anything like this, but there's always someone who knows! class FitFileDetailView(DetailView): model = FitFiles fitfile = FitFile(insert location of file associated with object) -
django image ,guidance needed please
i just want to know if there is an image viewer framwork or something so i can display it in my and template and have the functionalities like zoom scroll ..etc ? i will add a randon django code in here with no reason , because i can't post my question from django.shortcuts import render from django.db.models import Q from django.views.generic import TemplateView,ListView # Create your views here. def search(request): template='categories.html' query=request.GET.get('q') results=Gigposter.object.filter(Q(title__icontains=query)) -
Bootstrap table formatting wrong in Chrome but correct in Firefox
I have a bootstrap table which is formatted completely correctly in Firefox but is all thrown to the right on Chrome. Any ideas? Firefox: Chrome: I originally thought it might be something to do with it being within a table-responsive div but I removed that and it made no difference. Here's the HTML: <div class="row"> <div class="col"> <table class="table"> <tr> <th class="col-1 text-center"><input class="form-check-input position-static" type="checkbox" id="checkAll" value="option1"></th> <th class="col-2"><a class="text-body" href="?page={{ contacts.number }}&order_by=displayName">Name</a></th> <th class="col-3 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=companyName">Organisation</a></th> <th class="col-3 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=jobTitle">Job Title</a></th> <th class="col-1 d-none d-md-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=profession">NSO</a></th> <th class="col-1 d-none d-lg-table-cell"><a class="text-body" href="?page={{ contacts.number }}&order_by=lastModifiedDateTime">Last Updated</a></th> <th class="col-1">Profile</th> </tr> {% if contacts %} {% for contact in contacts %} <tr> <td class="col-1 text-center"><input class="form-check-input position-static" type="checkbox" id="blankCheckbox" name='selected_contact' value={{ contact.per_contact_id }}></td> <td class="col-2"><a href="mailto:?bcc={{ contact.emailAddresses.0.address }}" class="text-primary">{{ contact.displayName }}</a></td> <td class="col-3 d-none d-lg-table-cell">{{ contact.companyName }}</td> <td class="col-3 d-none d-lg-table-cell">{{ contact.jobTitle }}</td> <td class="col-1 d-none d-md-table-cell">{{ contact.profession }}</a></td> <td class="col-1 d-none d-lg-table-cell">{{ contact.modified }}</td> <td class="col-1"><button name="submit_button" type="submit" class="btn btn-link text-success noline" value={{ contact.per_contact_id }}>View</button></td> </tr> {% endfor %} {% endif %} </table> </div> </div> -
Virtual Environment's Activate Does Nothing
I searched a lot for the solution to this issue but I guess fewer people are having the same problem as mine. So, I switched to my new laptop and tried to install VirtualEnv on the latest version of Python. Even though it is successfully installed, when I create a new virtual environment and try to activate it, it switches to a new line as nothing has happened. I checked the folder, I'm entering the right path, it's not in "bin" folder. I'm not sure what's causing the problem. I have to note that I'm on Windows and I'm not using PowerShell. any ideas? P.S. Please note that I know that it must show the VirtualEnv's name in parenthesis but unfortunately, it doesn't. -
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'; …