Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get objects data trough txt docs
i've to recreate my project, for some data problems that i've got, them i'm trying to use some commands to import the data propperly. i'm having a problem by having to get a field from one doc.txt and other field pro other doc.txt but both fields from the same model. create_data.py from django.core.management.base import BaseCommand from c2vconfig.models import MP4, Tutorial class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'file_name', type=str, help='') def handle(self, *args, **kwargs): with open('nomes.txt') as file: for row in file: nome = row with open('urls.txt')as file: for row in file: url = row mp4 = MP4( nome=nome, url=url, ) mp4.save() self.stdout.write(self.style.SUCCESS('Data imported successfully')) models.py: class MP4 (models.Model): nome = models.CharField(max_length=100) url = models.URLField(max_length=300) preço = models.DecimalField(max_digits=5, decimal_places=2) imagem = models.ImageField(upload_to='', blank=True) artista = models.CharField(max_length=100, default='Unknown') nomes.txt Somewhere over the Rainbow people urls.txt https://www.youtube.com/watch?v=V1bFr2SWP1I&list=RDV1bFr2SWP1I&start_radio=1 https://www.youtube.com/watch?v=KDxJlW6cxRk&list=RDVHoT4N43jK8&index=19 its returning me just the last row from nomes.txt as MP4.nome and getting the MP4.url one by one as should be -
How to pass a custom model manager queryset to a template
I am trying to pass a custom query to a template but the query results are not being displayed. I had a working solution for this but I wanted to implement a custom model manager to simplify the code but I cant get the final step work - that is displaying the results on the template I have a custom manager: from django.db import models class ProfileQuerySet(models.QuerySet): def get_users_follows(self, user): print(user) return self.filter(followed_by__user__username=user) class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model, using=self._db) def get_users_follows(self, user): return self.get_queryset().get_users_follows(user) which is instantiated in the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) objects = ProfileManager() my view is as follows: class FollowsListView(LoginRequiredMixin, ListView): # Follow.follow_data = [[],[]] model = Profile template_name = 'blog/follows.html' # <app>/<model>_<viewtype>.html # paginate_by = 6 def get_queryset(self): follow_data = Profile.objects.get_users_follows(self.request.user) context = {'follow_data', follow_data} return context In the template i am calling the follow_data like so: {{ follow_data }} {% for p in follow_data %} {% if p.user %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ p.user.profile.image.url }}" alt=""> <a href="{% url 'user-posts' p.user %}">{{ p.user.profile.user }}</a> {% else %} <p>You are not following any users</p> {% endif %} </article> {% endfor … -
DataTables, serverSide and pagination on Django
I use DataTables with serverSide render. <script> $(document).ready( function () { $('#myTable').DataTable({ "processing": true, "serverSide": true, "ajax": "{% url 'core:persons_json' %}", "columns": [ {"data": "full_name"}, {"data": "email"}, ] }); }); </script> In my views.py i have: def persons_json(request): persons = Person.objects.all() data = [item.to_dict_json() for item in persons] page = 1 per_page = 10 res = { 'data': data, 'page': page, 'per_page': per_page, 'total': math.ceil(persons.count() / per_page) } return JsonResponse(res) But still he still returns all the persons. And I want to avoid loading a lot of data. But when i define, for example: def persons_json(request): length = int(request.GET.get('length')) persons = Person.objects.all()[:length] data = [item.to_dict_json() for item in persons] page = 1 per_page = 10 res = { 'data': data, 'page': page, 'per_page': per_page, 'total': math.ceil(persons.count() / per_page) } return JsonResponse(res) length = int(request.GET.get('length')) is parameter send by serverSide: http://localhost:8000/person/json/?draw=1&columns%5B0%5D%5Bdata%5D=full_name&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=email&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1568072064631 Note that we have: start=0&length=10. My question is as follows: when I use this second option. The pagination of other items does not appear in DataTables, ie I wanted it here but only one page appears. Does anyone know how I do to return all pages, and I go clicking each to advance the pages? -
404 on django pipeline staticfiles when using multiple deployments with different app versions
I have two different websites that run the same app but they may differ a bit in their versions. The problem I am encountering is when I deploy one site, if the version hash changes, the other site breaks as well. It looks to me like the hashes are stored in an external resource. How do I force each instance of the application to serve their own version of the staticfiles? Here are my configs: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', 'pipeline.finders.CachedFileFinder', #'django.contrib.staticfiles.finders.DefaultStorageFinder', ) -
mitmproxy failed with error 'no current event loop ...'
i try to start a mitmproxy instance as a thread from a django api call. Here my code: class Proxyserver(threading.Thread): def __init__(self): threading.Thread.__init__(self) opts = options.Options(listen_host='127.0.0.1', listen_port=8080) opts.add_option("body_size_limit", int, 0, "") opts.add_option("ssl_insecure", bool, True, "") config = proxy.ProxyConfig(opts) self.proxyserver = DumpMaster(opts) self.proxyserver.server = proxy.server.ProxyServer(config) self.proxyserver.addons.add(AddonProxy) def run(self): asyncio.set_event_loop(self.proxyserver.channel.loop) self.proxyserver.run() def stop_proxy(self): self.proxyserver.shutdown() proxythread = Proxyserver() proxythread.start() The error message is: Internal Server Error: /api/testcall_recrawl Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/usr/bin/testcall/api/views.py", line 22, in post thread = threading.Thread(target=start_crawler()) File "/usr/bin/testcall/api/crawler.py", line 255, in start_crawler proxythread = Proxyserver() File "/usr/bin/testcall/api/crawler.py", line 152, in __init__ self.proxyserver = DumpMaster(opts) File "/usr/local/lib/python3.7/dist-packages/mitmproxy/tools/dump.py", line 24, in __init__ super().__init__(options) File "/usr/local/lib/python3.7/dist-packages/mitmproxy/master.py", line 48, in __init__ asyncio.get_event_loop(), File "/usr/lib/python3.7/asyncio/events.py", line 644, in get_event_loop … -
FOREIGNKEY Constraint failed
I'm having trouble getting my code to work. I can't seem to add second item to the database when I call this in views.py: def create_item(request): context = {} if not request.user.is_authenticated: return redirect("social:begin", "google-oauth2") if not checkrights(user=request.user, venue=request.user.currentVenue): print("Not verified") return redirect("dashboard:venues") context["venueList"] = [admin.venue for admin in request.user.administrates.all()] context["form"] = NewItemForm(currentVenue=request.user.currentVenue) context["cableForm"] = NewCableForm() context["adapterForm"] = NewAdapterForm() context["fixtureForm"] = NewFixtureForm() if request.method == "POST": itemForm = NewItemForm(data=request.POST, currentVenue=request.user.currentVenue) cableForm = NewCableForm(request.POST) adapterForm = NewAdapterForm(request.POST) fixtureForm = NewFixtureForm(request.POST) if cableForm.is_valid(): subItem = cableForm.save(commit=False) itemType = Type.objects.get(pk=3) print("Cable") elif adapterForm.is_valid(): subItem = adapterForm.save(commit=False) itemType = Type.objects.get(pk=2) print("Adapter") elif fixtureForm.is_valid(): subItem = fixtureForm.save(commit=False) itemType = Type.objects.get(pk=1) print("Fixture") if itemForm.is_valid() and subItem: item = itemForm.save(commit=False) item.itemType = itemType item.location = item.home item.out = False item.holder = None item.save() item = Item.objects.get(pk=item.id) subItem.id = item print(subItem.pk) subItem.save() return redirect("dashboard:detail", item_id=item.id) return render(request=request, template_name="dashboard/new_item.html", context=context ) This is my models.py: class Item(models.Model): id = models.AutoField(primary_key=True) itemType = models.ForeignKey(Type, on_delete=models.CASCADE, null=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="items") home = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="item_homes") out = models.BooleanField(null=True) holder = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name="holding") # owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=False, related_name="owns") class Fixture(models.Model): modelType = models.ForeignKey(Type, on_delete=models.CASCADE, default=4, related_name="fixtures") id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.ForeignKey(FixtureType, … -
django-saml2-auth: Infinite Redirects on Login
I'm completely new to django-saml2-auth (and SAML2 with Django in general) and am trying to get it working with Microsoft ADFS. When I hit my Django app it successfully redirects me to the federated login page, but after providing valid credentials, the app then goes into a loop where it's just flipping back and forth between my ENTITY_ID URL (which is https://myapp/saml2_auth/acs/) and a URL on the ADFS server with continually changing SAMLRequest values as a URL parameter. The only clue I have to go on at this point is when I check my browser history, eventually one of the page titles for all this activity in the history is "SigVer Error" but after some cursory googling I'm not sure what that might mean. I saw some references to disabling signed responses at the pysaml2 level but didn't want to go too far with that without first trying to figure out if that's even the issue given the behavior I'm seeing. Any ideas? I can share my settings if that'd be helpful but the only optional setting I'm adding is the ENTITY_ID value since that's required by ADFS. Debugging is also a bit of a challenge since at this point … -
Django download excel file results in corrupted Excel file
I am trying to export a Pandas dataframe from a Django app as an Excel file. I currently export it to CSV file and this works fine except as noted. The problem is that when the user open the csv file in Excel App, a string that looks like numbers .... for example a cell with a value of '111,1112' or '123E345' which is intended to be a string, ends up showing as error or exponent in Excel view; even if I make sure that the Pandas column is not numeric. This is how I export to CSV: response = HttpResponse(content_type='text/csv') filename = 'aFileName' response['Content-Disposition'] = 'attachment; filename="' + filename + '"' df.to_csv(response, encoding='utf-8', index=False) return response To export with content type EXCEL, I saw several references where the following approach was recommended: with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() return HttpResponse(b.getvalue(), content_type='application/vnd.ms-excel') When I try this, It appears to export something, but if I try to open the file in Excel Office 2016, I get a Excel message that the file is corrupted. Generally the size is few KB at most. Please advise what could be wrong … -
Pagination with ListView django
I want to create app with search and pagination. Pagination didn't work with ListView. When I click on the link "next" I am moving from start page http://127.0.0.1:8001/ ---> to the http://127.0.0.1:8001/?city=2 but elements of the list did not change. And next click to the "next" link did not changes the url ( http://127.0.0.1:8001/?city=2 --> http://127.0.0.1:8001/?city=2). Could you help me to find error? I think that error in *.html file, but can't find it My code: models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) class Meta: verbose_name_plural = "cities" def __str__(self): return self.name urls.py # cities/urls.py from django.urls import path from . import views from .views import HomePageView, SearchResultsView urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView from .models import City from django.db.models import Q from django.shortcuts import render, get_object_or_404 class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list home.html <!-- templates/home.html … -
The best pythonic way to include attributes in Q lookup using dictionary with the condition "OR"
When I include attributes in Qlookup using dictionary, they are used with the condition "AND". How best to set the condition "OR"? from django.db.models import Q query={'manufacturer':'1','release_date':'2019'} lookups = Q(**query) print(lookups) # (AND: ('manufacturer', '1'),('release_date', '2019')) I would like to see something like " (OR: ('manufacturer', '1'),('release_date', '2019')) " Thank you in advance. -
Django-filer, URL that is 'seperate' from admin
I am trying to set up django-filer on my website. I cannot figure out how to get the URLS to be separate from the admin site on the website. localhost:8000/admin/filer/folder/ Is where it wants to go now, which of course requires someone to have complete admin access in the /admin portion. I want them to have just filer access and be able to see the site. I have my base urls.py as: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), # new path('accounts/', include('django.contrib.auth.urls')), path('filer/', include('filer.server.urls')), ] Going to localhost:8000/filer does nothing though? I was hoping I was able to create a local little dropbox functionality with my django website where registered users can use it, though they don't have to be admin in the /admin Is this even possible? I didn't see it in the documentation for filer at all? -
Django trigger script inside multiple different popups
I am new to django and trying to run a script when a user clicks on a confirmation button located inside a popup. This button is located inside a table that contains various information, including an ID, which I would like to pass to the script. Here is the table in the index.html file {% for st in scrapestats %} <tr> <td class="text-left">{{st.market}}</td> <td>{{st.start|date:"Y-m-d H:i:s"}}</td> <td>{{st.end|date:"Y-m-d H:i:s"}}</td> <td>{{st.finished_count}}/{{st.total_count}}</td> <td><a href="#"><span class="badge">{{st.ads}}</span></a></td> <td><a href="#"><span class="badge">{{st.ads_feedback}}</span></a></td> <td><a href="#"><span class="badge">{{st.user}}</span></a></td> <td><a href="#"><span class="badge">{{st.seller_feedback}}</span></a></td> <td><button type="button" name={{st.process_id}} class="btn btn-danger btn-xs confirm" data-toggle="modal" data-target="#Modal-{{st.process_id}}"> Revert </button> <!-- Modal --> <div class="modal fade" id="Modal-{{st.process_id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title" align='left' id="delete-server-{{st.process_id}}">Are you sure you want to delete process id {{st.process_id}} ?</h5> </div> <div class="modal-body" align='left'> This might be dangerous ! </div> <div class="modal-footer"> <!-- <form action="#" method="POST" id="call_delete_server"> --> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" id="confirm_deletion" data-id={{st.process_id}} class="btn btn-primary">Delete</button> <!-- </form> --> </div> </div> </div> </div> </tr> {% endfor %} And the script, also in the index.html <script> $("#confirm_deletion").click(function (e) { console.log($(this).attr("data-id")); }); </script> What happens is that when I click on the last button in the {% for st in scrapestats %} loop, it correctly outputs … -
Django: Could not parse the remainder: ': "cht"' from 'chart_list|load_charts: "cht"'
I want to embed graphs into my django project and I am now trying out chartit. It looks promising, especially because it can be modified inside the view. views.py from chartit import DataPool, Chart from .models import SalesReport def sales(request): sales = DataPool( series= [{'options': { # 'source': SalesReport.objects.all()}, 'source': SalesReport}, #'source': SalesReport.objects.filter(sales__lte=10.00)}, 'terms': [{'month': 'month', 'sales': 'sales'}] }, ]) def monthname(month_num): names = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'} return names[month_num] #Step 2: Create the Chart object cht = Chart( datasource = sales, series_options = [{'options':{ 'type': 'column', 'stacking': False}, 'terms':{ 'month': [ 'sales'] }}], chart_options = {'title': { 'text': 'Sales Amounts Over Months'}, 'xAxis': { 'title':{'text': 'Sales Total'}}, 'yAxis': { 'title': {'text': 'Month Number'}}, 'legend': { 'enabled': True}, 'credits': { 'enabled': True}}, x_sortf_mapf_mts=(None, monthname, False)) #Step 3: Create a second chart object cht2 = Chart( datasource = sales, series_options = [{'options':{ 'type': 'pie', 'plotBorderWidth': 1, 'zoomType': 'xy', 'legend':{ 'enabled': True, }}, 'terms':{ 'month': [ 'sales'] }}], chart_options = {'title': { 'text': 'Sales Amounts Over Months - Pie Chart'}, 'xAxis': { 'title':{'text': 'Sales Total'}}, 'yAxis': { 'title': {'text': 'Month Number'}}, 'legend': … -
Get model name for absoulte url in django 2
Im newi in django and tried to showing absolute path and pass to my template in django I have model and want use one of field to user by loop in template Models.py calss KPI(models.Model): name=models.Charfield(max_length=100) category=models.ForeignKey(category,related_name='categorys' , one_delete=models.CASCADE) Views.py def dashbaords(request): category_list = category.objects.all() category_url = request.build_absolute_uri() return render (request,Dashboard.html,{'category_list':category_list,'category_url',category_url} urls.py urlpattern:[ path{'<int:pk>/',views.dashboards,name='dashbaords'), ] template: {% for category in domain.categorys.all %} <li> <a href={{category_url}}></li> {{category.name}} </a></li> Now url shown 127:0.0.1/dashbaord1 But get error page not found and not shown dashbaord.html after im going to absolute url for them -
As maintain a new post responding only on one button, "Save"?
On the page of adding a post there are fields and buttons to select the relief / background. But when you click on any button is saving the post. How to implement the creation of posts, reacting only to one button "Save"? If now when you press any button in ... the post is saved. It is necessary that when you click other buttons, there was a change in the Iframe without reloading the page {% load static %} <head> <meta charset="UTF-8"> <link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /> <link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /> <title>Creating presentations</title> <script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Arya" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../static/css/cssmenu.css"/> <link rel="stylesheet" href="{% static 'css/cssmenu.css' %}"> <style> body { font-family: "Arya", sans-serif; display: flex; } body #left { text-align: left; } body #left h2 { margin: 15px 0px 0; } body #left #select { display:inline-block; } body #left #select #color , body #left #select #picture { display:inline-block; flex-direction: column; padding: 0px 0px; } body #left #select #color button, body #left #select #picture button { font-family: "Arya", sans-serif; padding: 18px 18px; outline: none; cursor: pointer; border: none; border-radius: 5px; box-shadow: 0 0px #95a5a6; margin: 8px 0px; font-size: 12px; display: inline; } body #left #select … -
Django PostgreSQL - Fuzzy Searching on single words
I'm using Django's builtin trigram_similar lookup and TrigramSimilarity class to create a fuzzy searching using a PostgreSQL database. This way, I filter titles of articles. The problem is, this filters based on the whole title. I want to filter it also on parts on title. Example: Title of Article: "We are the world | This is the best article ever". My search: "we" In this example, my function returns nothing, but I want it to return this article. How can I do that? This is the code I use: def search(qs, term, fields=["title"], treshold=.3): if len(fields) >= 2: return qs.annotate( similarity=Greatest( *[TrigramSimilarity(field, term) for field in fields] ) ).filter(similarity__gte=treshold).order_by("-similarity") return qs.filter( **{"{}__trigram_similar".format(fields[0]): term} ) -
Display data in tabular format from database in web page for more than 100,000
I have more than 100,000 transactions in the Database on a daily basis. I want to display it in tabular format on the client-side(e.g web site). Q1: Which javascript or python library should I use? Q2: Can javascript or python library display the data, What if data exceeds more than 1 million. Q3: Can javascript or python library display the data, if data exceeds more than 1 million like after 10 days e.g if the user is interested in the last two to 3 days transaction history. -
How to loop through a list of dictionaires in another file on a block code on an html file?
This is kinda hard to explain. I'm building a web app using Django and I created a template in which a for loop loops through a list of dictionaires on the views.py file. Then when I run the website is a blank page. I'm using PyCharms and I've tried to inject a language on the block of code, Python and Html, but when injecting python it says that list is not defined and when using Html the website is just blank. If I don't inject a language it says that there is a typo on the word endfor. #list on views.py file posts = [ { "author": "Telmo Antunes", "title": "Blog post 1", "content": "First Post Content", "date_posted": "September 9th, 2019"}, { 'author': "Telmo Antunes", 'title': "Blog post 2", 'content': "2nd Post Content", 'date_posted': "September 9th, 2019"} ] #template <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{ post.content }}</p> {% endfor %} </body> I was expecting the output on the website to be Blog post 1 By Telmo Antunes on September 9th, 2019 First Post Content Blog post 2 By Telmo Antunes on September 9th, 2019 2nd Post Content -
How get the Engine value of my server when this dont included in the django default settings
i am new in programation web with python, and have a problem with the connection to my database, i have already the values of name, user, pass, host, but for the connection requires too Engine value, the database dont belongs to any server predeterminates , like mysql, sqlLite, postgre etc ... i i dont know how get this value, the documentation says configure to a fully qualified path(mypackage.bakend.whaterver). Anyone know? Regards django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
Django Rest API's sub routes are not accessible on AWS Elastic Beanstalk
I have a Rest API developed with Django Rest Framework. It is completely functional when running locally with: python manage.py runserver All requests work as expected: 127.0.0.1:8000/ 127.0.0.1:8000/projects/ Now the issues arise when deploying from a cloud service such as AWS Elastic Beanstalk or Google App Engine. The defaut route works fine as shown below. The projects route however does not load. The request code received varys by platform. App Engine give a 502 Bad Gateway code and Beanstalk gives a 504 Gateway Timeout. With Beanstalk, running eb logs reveal no errors. projects-restapi-dev.us-west-2.elasticbeanstalk.com/ projects-restapi-dev.us-west-2.elasticbeanstalk.com/projects I'm certain the issue has something to do with how i'm routing my views. Here's my urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path, include from projects.views import ProjectView from rest_framework import routers router = routers.DefaultRouter() router.register(r'projects', ProjectView) urlpatterns = [ path('', include(router.urls)), path("projects/", ProjectView), path("admin/", admin.site.urls), path("api-auth/", include('rest_framework.urls')) ] Also, here's a link to the github repo if you need to see any other files. -
What is the difference between using Python's Request library and Django's APICient from a unit test
I am trying to write unit tests for an Django OAuth2 API. I am using Django's APIClient library. if I use it from a Django shell. it works perfectly, but if I use is in a unit test, the POST request to the view works fine (200 OK), however the post inside of the view's function, fails with 400 bad request. If the user already exists in the database, the Unit test works fine and an access code is returned. if not, it fails. The API POST request to the view works from Postman. it works inside a unit test using Python's Requests library. All requests from a Django shell work (APIClient, Requests, RequestsClient, APIRequestFactory). For this reason, I am guessing that it is a Middleware issue? However, why does unit test using Requests work, yet all the other libraries fail? I understand that unit tests run on a different database to the application server, but even when I change the SETTINGS so that the Tests use the same SQLite database as the application server, the results are the exact same. ### This works perfectly in a Django Shell from rest_framework.test import APIClient client = APIClient() response = client.post('http://127.0.0.1:8000/authentication/register/',{"username": "testuser17", … -
Authentication credentials were not provided drf
when i trying to access api i'm getting this error: "detail": "Authentication credentials were not provided." i have included this in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ) } my app api urls.py: from django.urls import path,include from . import views from rest_framework import routers router = routers.SimpleRouter() router.register(r'',views.UserViewSet, 'user_list') urlpatterns = router.urls my views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.object.all() serializer_class = serializers.UserSerializers my main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('',include(urls)), path ('', include(user_urls)), path('api/',include(api_urls)), when i running localhost:8000/api i'm getting the error -
Django-select2 selects pk (IntegerField) instead of username (CharField) and fails
My goal is to create a form to add a rental for a device including a user. Device and user are implemented with a ForeignKey, and for the user i want to use django-select2 , because of the heavy amount of users. models.py class Device(models.Model): name = models.CharField( verbose_name = "Gerätename", max_length = 128, unique = True, ) def __str__(self): return self.name class ldap_data(models.Model): username = models.CharField(max_length=1024, unique=True) class Meta: ordering = ('username',) def __str__(self): return self.username class Rental(models.Model): user = models.ForeignKey(ldap_data, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) date_start = models.DateField() date_end = models.DateField() class Meta: ordering = ('date_start',) def __str__(self): return self.device forms.py class RentalForm(forms.ModelForm): user = forms.ChoiceField( widget=ModelSelect2Widget( model=ldap_data, search_fields=['username__icontains'] ) ) date_start = forms.CharField(label="Datum Ausleihe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) date_end = forms.CharField(label="Datum Rückgabe", help_text="", widget=forms.TextInput(attrs={'id': 'datepicker2', 'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) class Meta: model = Rental fields = ['device', 'user', 'date_start', 'date_end',] The form works so far, but if i select a user from the django-select2 field user, the form complains, Select a valid choice. 1 is not one of the available choices. It looks like the form tries to validate the pk (=1) of the selected user, instead of the username … -
How to fix "AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'"
I have a coding interview tomorrow (my first ever! Super excited/nervous) and am working to bring an old project of mine back to life and updated: a producthunt clone built in Django/Python. Everything used to run fine with it and now, after git cloning it into a ubuntu virtualbox and bringing things up to date in its virtualenv, I'm stuck with the following error and have come up empty handed after hours of troubleshooting and researching similar issues on stackoverflow. Any help is appreciated. The error: 'AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'' Settings and output: settings.py """ Django settings for producthunt project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@(b=ndac@9k%w#y7(h5p!^a!)6y_p2&oln@lsz6x61=wyusg4(' import os import django django.setup() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ROOT_URLCONF = 'producthunt.urls' ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'compressor', … -
django-extensions: graph_models: What is the meaning of double circle dots indicate
I have created a model_graph by python manage.py graph_models -a -o basic_django_models.png This is a small part of it What is the meaning of line with double circular dots (i.e circular dot on each ends). Between Group and Permission in the above diagram. I understood single dot as foriegn key like between Content_type and Permission