Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found when opening link as new window
Getting the error message; Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/students/undefined When I try and open a link as a new window on Django, this is the code I wrote; <a href="#" onClick="MyWindow=window.open('https://www.youtube.com/watch?v=fNk_zzaMoSs','MyWindow','width=600,height=300'); return false;">Click Here</a> The YouTube video opens in a new window, but I get the error message in my initial window, the one with my current project open -
Django - How to get model id when clicked on it
My django application purpose is so simple: user solves algorithm from some source (for instance, Hackerrank), and returns back to my application and sends feedback about result (these algorithms are given to users by me as a task). Now I want to get id of task when clicked on send button after feedback wrote. Because from admin dashboard I could see feedback was written for which task. BTW, I'm getting no such column: algorithmtrackerapp_taskfeedback.task_id error because of thinking task as a foreign key for feedback. Here are my codes: views.py: def index(request): tasks = Task.objects.all().order_by('-task_deadline') task_feedbacks = TaskFeedback.objects.all() form = CreateFeedbackForm() context = { 'tasks': tasks, 'task_feedbacks': task_feedbacks, 'form': form } if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return render(request, 'index.html', context) models.py: class Task(models.Model): task_name = models.CharField(max_length=100) task_url = models.URLField(max_length=300, blank=True, null=True) task_source = models.CharField(max_length=50, blank=True, null=True) task_deadline = models.DateTimeField() uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.task_name class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=500, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content This is my interface: -
DRF Serializers taking a lot of time to execute , What other option do i have to send the serialized response in DJANGO
So I am trying to send complex nested JSON response from one of the endpoints in API developed in DJANGO , I am using DRF for that purpose , they're great but they're really slow . I was wondering what other option do I have . The response needs to be serialized and it's nested , complex . DRF Serializers were working great until the dataset grew and now it's really slow . -
Pytest failing to import third-party packages
So I am stuck with pytest. My setup is a django setup with docker-compose. Anytime I run pytest, I get errors like this Hint: make sure your test modules/packages have valid Python names. Traceback: lib/python3.6/site-packages/compressor/tests/test_signals.py:4: in <module> from mock import Mock E ModuleNotFoundError: No module named 'mock' another one E _pytest.config.ConftestImportFailure: (local('/app/lib/python3.6/site-packages/testfixtures/tests/conftest.py'), (<class 'ModuleNotFoundError'>, ModuleNotFoundError("No module named 'sybil'"), <traceback object at 0x7fb8a7a4e780>)) Seems like it's having problem importing third-party libs, how do I ignore these kinds of errors. -
django-plotly-dash serve css files locally
I am trying to serve css files locally in a DjangoDash app using django-plotly-dash. Simpleexample.py app = DjangoDash('SimpleExample', serve_locally=True) app.css.append_css("path_to_css") app.layout = html.Div([ html.Div( className="app-header", children=[ html.Div('Plotly Dash', className="app-header--title") ] ), html.Div( children=html.Div([ html.H5('Overview'), html.Div(''' This is an example of a simple Dash app with local, customized CSS. ''') ]) ) ]) simpleexample.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} {% plotly_app name='SimpleExample' ratio=0.45 %} </div> {% endblock %} header.css and topography.css are the files as described here: https://dash.plotly.com/external-resources. According to these: https://github.com/GibbsConsulting/django-plotly-dash/issues/121 and https://github.com/GibbsConsulting/django-plotly-dash/issues/133, the issues regarding this should be fixed. However the css styling does not render-- What am I missing here? There was a suggestion in the above github issues that we can use django template rather than iframe. I could not find much documentation on that -- can anyone point me there? Thank you. -
Django Manytomany Autocomplete Lookup
Is it possible to adopt the Django many to many autocomplete loopup for form? I know how to adopt the Django normal loopup but not the many to many with autocomplet outside of admin page. For the normal loopup this will work by adding this into the html template: <a onclick="return showRelatedObjectLookupPopup(this);" class="related-lookup" id="lookup_id_object" title="Lookup" href="/admin/..."></a> -
Django search form with multiple filter
in my Django web site I've got a User page where are listed all the items the User added to the database. There's a search form for the user to search into its own items. The problem is that the search form doesn't work. I'm a little bit confused about how to filter through the database because, first I've filtered all the items in order to show only the ones added by the User logged, and then I should filter through these based on the user input. Hope someone could help me, thanks! The 'def look()' is what I tried but doesn't work Views.py class userListView(ListView): model = Info template_name = 'search/user.html' paginate_by = 10 def get_queryset(self): qs = super().get_queryset() qt = qs.filter(utente=self.request.user) return qt def look(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['cerca'])) srch = request.POST.get('cerca') if srch: sr = Info.objects.filter(srch = Subquery(qt)) if sr: return render (self.request, 'search/user.html', {'sr':sr}) else: return render(self.request, 'search/user.html') else: return render(self.request, 'search/user.html') user template html <div class="add"> <div class="posted"> <div class="head"> <h2> YOUR LIST </h2> <div class="form"> <form method="post" action="{% url 'user' %}"> {%csrf_token%} <input type="text" name="cerca" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> </div> </div> … -
Django - Foreign key, admin and forms
I’m working on a Django Project (i’m a beginner) and i have a small problem. I have different model with Foreign_Key. And also I have Forms to implements model. My problem, is not to big i think : I want the id + name instance on my admin or on my forms. Actually i have the value in def __str__(self): return self.nom I can’t do return self.id because it’s Int type. example of my models.py class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) adresse = models.CharField(max_length=100, blank=True, null=True) cp = models.CharField(max_length=5, blank=True, null=True) ville = models.CharField(max_length=50, blank=True, null=True) dessinateur = models.PositiveSmallIntegerField(blank=True, null=True) conducteur = models.PositiveSmallIntegerField(blank=True, null=True) chefdeprojet = models.PositiveSmallIntegerField(blank=True, null=True) cloture = models.IntegerField() class Meta: managed = True db_table = 'affaires' def __str__(self): return self.nom Have you got an idea ? -
Caching on Django Rest Framework GenericViews
I don`t find infos on how caching of Django Rest Framework generic views is configured. Do I have to override the get message and add an own @method_decorator? This feels ungeneric to me. class BlogTags(generics.ListAPIView): queryset = CustomContentBlogTag.objects.all() serializer_class = CustomContentBlogTagSerializer permission_classes = [AllowAny] @method_decorator(cache_page(60 * 60 * 24)) def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) Docs I found: Caching: https://www.django-rest-framework.org/api-guide/caching/ Generic views: https://www.django-rest-framework.org/api-guide/generic-views/ In the generic views docs, there is a sentence, that the queryset is cached somehow. But what, if I want the whole view to be cached? -
Order a form in a django formset by overriding __iter__ and __getitem__ method
I am using Django inlineformset_factory and i want to order a form based on the form instance foreign key in ascending order. I research on django documentation on how to order the django formset and the answer is using the iter and getitem method. But the problem in my code is I am being unable to sort the django formset yet. -
This site can’t be reached mysite.com refused to connect. ERR_CONNECTION_REFUSED
I am trying to add social authentication to my Django project and because of this I need to be able to do this: mysite.com:8000/account/login/ instead of this: 127.0.0.1:8000/account/login/ I'm on Ubuntu 16.04 running chrome Version 81.0.4044.92 (Official Build) (64-bit) I have updated INSTALLED_APPS in the settings file in Django to read: ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] And added the following in /etc/hosts 127.0.0.1 mysite.com I have also cleaered the chrome cache but I still get the following error: "This site can’t be reached mysite.com refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" Does anyone know how I can get this to work please? Or even suggest another way to do it. -
How to have 2 different models for user and admin in django and how to manage them?
I am trying to create a social media type website where users can post images, videos, blogs, and meantime they can see other user's postings. I want to have 2 different models. One for users and another only for admins and moderators of the website. Admin and moderators can log in to the admin panel and edit the website. The users can only post certain things, delete their posts or update and add other users as friends/followers. In default option in Django, the users and admins are in the same model/table of a database. So is there any way to separate them? The users will be able to log in to the website. If I create 2 different models for users and admin how will I be able to authenticate the users when they will try to login to the base website where they will post things? How will I be able to set the Request.user? What will be my auth_user_model? I have created 2 different databases for this thing. One is for the admin and user DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'admin', 'USER': '#user', 'PASSWORD': '#password', 'HOST': 'localhost', 'PORT': '5432', }, 'user':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user', … -
Exception Value: string indices must be integers : Render bundle error vue + django
im using webpack loader to inyect my vue app into django, here is the code: Settings : WEBPACK_LOADER = { 'DEFAULT':{ 'BUNDLE_DIR_NAME':'/', 'STATS_FILE':os.path.join(BASE_DIR,'aptim-frontend/dist','webpack-stats.json') }} vue config file : const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://0.0.0.0:8080/", outputDir: "./dist/", chainWebpack: (config) => { config.optimization.splitChunks(false); config .plugin("BundleTracker") .use(BundleTracker, [{ filename: "../frontend/webpack-stats.json" }]); config.resolve.alias.set("__STATIC__", "static"); config.devServer .public("http://0.0.0.0:8080") .host("0.0.0.0") .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .headers({ "Access-Control-Allow-Origin": ["*"] });},}; And the html line where I get the error is at the index html {% render_bundle 'app' %} ERROR :Exception Value: string indices must be integers -
How to load django objects requesting DB once and do searches after
Suppose I have a QuerySet of all db entries: all_db_entries = Entry.objects.all() And then I want to get some specific objects from it by calling get(param=value) (or any other method). The problem is, that In documentation of QuerySet methods it is said: "These methods do not use a cache. Rather, they query the database each time they’re called.". But what I want to achieve is to load all data once (like doing Select *), and only after do some searches on them. I don't want to open a connection to the db every time I call get() in order to avoid a heavy load on it. -
How do I use arrays in Django models?
I have model of ShortURL, which contains some data. I want to collect metadata on each redirect (ip, time, etc), so I need to add ArrayField (which will contain dictionaries) of some sort. Didn't find anything such in docs, what do I do? -
django sql-server hot to bind checkbox values to a specific id in database
im new to django an programming with pyton and right now i am trying to bind checkboxes to a ID (not the primary Key. Right now i can write the value of the checkboxes to the database, but everytime i do that django makes an insert but i need to do an update to the database. I get the right id true the url. If i use instance= suddenly no checkbox is stored at all but the id is erased from the database. How can i bind the checkboxes to the posid in my database. So my database would be like id posid vegaplan mhd ve globalgap 74 1515 1 1 1 1 My form: class MyForm(ModelForm): class Meta: model = MyForm fields = '__all__' (Fields are: id(pk),posid, vegaplan, mhd, ve, globalgap my view: def MyView(request, posid): fid = MyModel.objects.get(posid=posid) form = MyForm(request.POST, instance = fid) if request.method == "POST": vegaplan = 'vegaplan' in request.POST mhd = 'mhd' in request.POST ve = 've' in request.POST globalgap = 'globalgap' in request.POST tosave= models.MyModel(vegaplan=vegaplan, mhd=mhd, ve=ve, globalgap=globalgap) tosave.save(form) return render(request, "pages.html") If some could help me or just give me a hind a would be very happy, right know i lost every … -
Using custom query in django-filters
I'm trying to filter a Model using Filterset (django-filter) and render from/to select form field in my Template. Unfortunately I cannot figure out how to get it working. While my code and power_category fields render fine, only a text field gets displayed when trying to render the reported field, unless I set type="date", then the datepicker pops up when clicking the date field; however only one shows up (need two, to, and from to select the range). -
Django query to remove older values grouped by id?
Im trying to remove records from a table that have a duplicate value by their oldest timestamp(s), grouping by ID, so the results would be unique values per ID with the newest unique values per ID/timestamp kept, hopefully the below samples will make sense. sample data: id value timestamp 10 10 9/4/20 17:00 11 17 9/4/20 17:00 21 50 9/4/20 17:00 10 10 9/4/20 16:00 10 10 9/4/20 15:00 10 11 9/4/20 14:00 11 41 9/4/20 16:00 11 41 9/4/20 15:00 21 50 9/4/20 16:00 so id like to remove any values that have a dupliate value with the same id, keeping the newest timestamps, so the above data would become: id value timestamp 10 10 9/4/20 17:00 11 17 9/4/20 17:00 21 50 9/4/20 17:00 10 11 9/4/20 14:00 11 41 9/4/20 16:00 -
django google map or other map saving lat and long data on user pointed location
This is my model: c lass Shop(models.Model): lat = models.CharField( max_length=300, null=True, blank=True, ) long = models.CharField( max_length=300, null=True, blank=True, ) and this is my form: <form method="POST"> {% csrf_token %} <input type="text" name="lat"> <input type="text" name="long"> <input type="submit" value="save"> </form> I am trying to implement, there will be a map in the frontend, when user put the mouse pointer on the map, the pointed location lat and long data should be filled in my form. I have read google map API documentation and i see the API key is Lil bit expensive for me. I am finding a way to fill the form field with lat and long when user click on specific location on a map, It is no problem if it is google map or bing or other, i just need a solution for free so when user click on a location, it should be fill the form. I know javascript has solution to get current location lat and long but this is not my business logic. CAN Anyone help me to achive this? -
Updating and saving dict in django with post requests
I am trying to make a responsive tournament bracket with python/django and using $.post requests to update a tournament dict - which I pass to a 'bracket' template as a dictionary, render, then update by $.posting the passed in variable to a nother view, which updates, saves to server, then redirects to 'bracket' view. I am just starting to make some progress, but having issues with reformatting of the bracket object. Little more detail The bracket is initialized in python (in my views.py) in a bracket view, but I am calling in the view a Tournament class that I got from here. the Tournament class takes a list of players and then generates a dictionary corresponding to the games with the method t.generate_bracket(). I kind of restructure this and then pass it into a bracket view for displaying - I display the restructured array in my template but also pass in the un-restructured one I have little radio buttons that are bound to a $.post 'update_bracket' view. In the JS $.post, I send the array to the view, where I will call a t.play_game() method to update the bracket. Then - instead of a JSON or HTTP response and subsequent … -
Opening YouTube video as a modal in Django
I am trying to play an embedded YouTube video as a modal in Django when a user clicks a link on my site. However I am getting the error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/students/undefined This is what i have tried <div class="media-body"> <i class="fa fa-fw fa-circle text-green-300"></i><a href="#" data-toggle="modal" class="video-btn img-fluid cursor-pointer" data-src="https://www.youtube.com/embed/<?= $row['fNk_zzaMoSs'] ?>" data-target="#myModal">Vectors and Spaces</a> </div> ..... <div class="modal videomodal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <!-- 16:9 aspect ratio --> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="" id="video" allowscriptaccess="always">></iframe> </div> </div> </div> </div> </div> .... <script type="text/javascript"> $(document).ready(function() { var $videoSrc; $('.video-btn').click(function() { $videoSrc = $(this).data( "src" ); }); console.log($videoSrc); $('#myModal').on('shown.bs.modal', function (e) { $("#video").attr('src',$videoSrc + "?rel=0&amp;showinfo=0&amp;modestbranding=1&amp;autoplay=1" ); }) $('#myModal').on('hide.bs.modal', function (e) { $("#video").attr('src',$videoSrc); }) }); </script> and my css .videomodal .modal-dialog { max-width: 800px; margin: 30px auto; } .videomodal .modal-body { position:relative; padding:0px; } .videomodal .close { position:absolute; right:-30px; top:0; z-index:999; font-size:2rem; font-weight: normal; color:#fff; opacity:1; } .cursor-pointer{ cursor: pointer; } -
Change one instance variable when creating another instance
I am making an app to create repair work orders which also has an inventory app in it. I create and edit repair work orders using class-based views. I have a model for work orders; class Order(models.Model): """Maintenance work orders""" ... parts = models.ManyToManyField(Part, blank=True) and model for parts inventory class Part(models.Model): """List of company equipment""" partnum = models.CharField(max_length=20) amount_in_stock = models.PositiveIntegerField() price = models.FloatField(blank=True, null=True) vendr = models.ManyToManyField('Vendor', blank=True) ... The idea is to add parts from inventory to order instances, and at the same time remove them from stock. What i can't figure out is, how i change instance variable Part.amount_in_stock from instance of Order. I create and edit orders using class-based views. The idea was i create a new sub-class class UsedPart(Part): """Part used in Repair""" used_in = models.ForeignKey('mtn.Order', on_delete=models.CASCADE) used_amount = models.PositiveIntegerField() def cost_of_repair(self, *args, **kwargs): super(Part, self).__init__(*args, **kwargs) price = self.price def __init__(self, *args, **kwargs): cost_of_repair = self.used_amount * price return cost_of_repair def __init__(self, *args, **kwargs): used_amount = self.used_amount super(Part, self).__init__(*args, **kwargs) self.amount_in_stock = self.amount_in_stock - used_amount And then i initiate it from Order UpdateView class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order But since i've only started learning python, i didn't get the hang of … -
how to solve gcloud app deploy network connectivity error?
When i try to deploy my django project on google app engine with command: gcloud app deploy then i got network connectivity error every time.Error massage is: ERROR: (gcloud.app.deploy) EOF occurred in violation of protocol (_ssl.c:661) This may be due to network connectivity issues. Please check your network settings, and the status of the service you are trying to reach. i try google but not solve it.Please anyone help me. my app.yaml file is : runtime: python37 entrypoint: gunicorn -b :8080 scanner_api.wsgi handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto -
Is it possible to reference a field in Django using brackets?
Hello I am trying to see if there is an ability to reference a model in Django using brackets //model class User(model.Model): firstname = models.charField() //referencing user = User.objects.get(id=1) //original reference user.firstname = "John" // proposed reference user["firstname"] = "John" Is this possible or are there any alternatived to the proposed reference -
Received incompatible instance in Graphql query
When i hit insomnia with this request bellow then it shows this response. How can i solve this issue ? Request: query{ datewiseCoronaCasesList{ affected, death, recovered } } Response: { "errors": [ { "message": "Received incompatible instance \"{'affected': 137, 'death': 42, 'recovered': 104}\"." } ], "data": { "datewiseCoronaCasesList": null } } My GraphQL query: class CoronaQuery(graphene.ObjectType): datewise_corona_cases_list = graphene.Field(CoronaCaseType) def resolve_datewise_corona_cases_list(self, info, **kwargs): return CoronaCase.objects.values('updated_at').aggregate( affected=Sum('affected'),death=Sum('death'), recovered=Sum('recovered')) My model: class CoronaCase(models.Model): affected = models.IntegerField(default=0) death = models.IntegerField(default=0) recovered = models.IntegerField(default=0) district = models.CharField(max_length=265, null=False, blank=False) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return "Affected from: {}".format(self.district)