Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
JQuery: Posting Files with FormData-Objects
So i am using a ModelForm for an updateview and want to append some files using a Javascript FormData-Object, submiting the whole form using JQuery. It seems, that the Image-Files dont get posted. views.py: class SowiUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView): def post(self, request, *args, **kwargs): print(request.POST) return super(SowiUpdateView, self).post(request, *args, **kwargs) The javascript: var formData = new FormData(document.getElementById("form_id")); for (var i = 0, len = filesToUpload.length; i < len; i++) { // filesToUpoad is a List containing a dict, with file i access the file formData.append("files", filesToUpload[i].file); } $.ajax({ headers: { "X-CSRFToken": getCookie("csrftoken") }, url: "{% url 'sowi-update' object.id %}", data: formData, contentType: false, processData: false, async: false, method: 'POST', type: 'POST', success: function (data) { // console.log(data); }, error: function (data) { console.log("ERROR - " + data.responseText); } }); Strangely, the serverside-post-data-output gives all the FormData-Data but the "files"-object. What's wrong? I Tried just appending a string instead of a file, and that worked. Thanks for your help!! -
Problems with creating session in the view
How to do that the same session but for each room, not for all of the rooms. In this case when this part working if user.has_perm('pass_perm', room) it creating this session request.session['joined'] = True but this works for all of the rooms views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) if request.session.get('joined', False): join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session['joined'] = True join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) -
django-simple-history is storing changes twice
I tried django-simple-history and I discovered that every create or update is stored twice in the history model. I don't know which information is now useful for you to help me, but I use CBV's and model forms. I followed the instructions on how to install and setup and everything works fine. What I'm wondering is why there is a command line called clean_duplicate_history, which indeed removes all duplicates records. Thank you in advance for any help. -
why docker terminal freezes on runing the command docker-compose up
i was creating a simple hello world in django using docker but it got stuck here -
Pycharm not autocomplet file path (Cannot find declaration to go to / No suggestions)
I'm developing two django projects in parallels, apparently with the same settings that I use to do, but in one of them, when I try to refer a file, the autocomplete does not suggest anything. Print above. Here other project with autocomplete working Both projects have the same template path settings. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join((BASE_DIR), 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] Any suggestions what it might be? -
Comparing request.user.username to data from database [closed]
I want to compare current user to sender of msg in db. But it is always false {%for msg in data%} {%if msg.sender == requset.user.username %} <div class="own-msg"> <p class="sender">{{msg.sender}}</p> <p class="content">{{msg.content}}</p> <p class="time">{{msg.date_created}}</p> </div> {%else%} <div class="msg"> <p class="sender">{{msg.sender}}</p> <p class="content">{{msg.content}}</p> <p class="time">{{msg.date_created}}</p> </div> {%endif%} {%endfor%} -
How to set the landing page for user after login with django-allauth
I have the following in my project's urls.py: path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), In my project's setting.py: LOGIN_REDIRECT_URL='survey/' When I am on the login page of my application and click to submit. Instead of getting http://localhost:8000/survey/ and being redirected to the home page of my application, I am getting: http://localhost:8000/accounts/login/survey/ that gives this error: Using the URLconf defined in TestAllAuth.urls, Django tried these URL patterns, in this order: admin/ accounts/ signup/ [name='account_signup'] accounts/ login/ [name='account_login'] accounts/ logout/ [name='account_logout'] accounts/ password/change/ [name='account_change_password'] accounts/ password/set/ [name='account_set_password'] accounts/ inactive/ [name='account_inactive'] accounts/ email/ [name='account_email'] accounts/ confirm-email/ [name='account_email_verification_sent'] accounts/ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] accounts/ password/reset/ [name='account_reset_password'] accounts/ password/reset/done/ [name='account_reset_password_done'] accounts/ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key'] accounts/ password/reset/key/done/ [name='account_reset_password_from_key_done'] accounts/ social/ survey/ ontoSecConRule/ The current path, accounts/login/usecase/, didn't match any of these. As you can see the usecase/ path is in the error message, but I am not reaching. Where do I set the page (url) after a user has been authenticated? -
Fargate : Uwsgi died because of signal 9 , Django project
I run Django project using uwsgi and fargate container, and container kept drained. This is cloudwatch log. DAMN ! worker 1 (pid: 22) died, killed by signal 9 :( trying respawn ... Strange thing is, I already running containers with the same project, same code as testing server, and this problem never happened. The only thing that different is I did not set auto-scaling on testing, and I set auto-scaling on this server. I would like to know what is the source of sending kill signal. -
How to index columns created by django-modeltranslation to Elastic, using django-elasticsearch-dsl?
I've translated my Model fields with django-modeltranslation and implemented search using django-elasticsearch-dsl. Problem: django-modeltranslation creates translation fields in DB, and not in my Models, and search is working only for fields created by Model. As django-elasticsearch-dsl is checking Models to rebuild search index. When I try: python3 manage.py search_index --rebuild I get the error: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/apps.py", line 14, in ready self.module.autodiscover() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/__init__.py", line 11, in autodiscover autodiscover_modules('documents') File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/barbos/django-symbolsite/symbolgraph/search/documents.py", line 7, in <module> class SymbolDocument(Document): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/registries.py", line 65, in register_document field_instance = document.to_field(field_name, django_field) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 142, in to_field "to an Elasticsearch field!".format(field_name) django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field name_ru to an Elasticsearch field! Oleh-MacSymbol-Pro:symbolgraph barbos$ python3 manage.py search_index --rebuild Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 138, in to_field model_field.__class__](attr=field_name) … -
Django rest framework return first date in objects
I am writing an API with the django rest-framework library. Now I have the following view: class Event(models.Model): id = models.CharField(db_column='Id', max_length=36, primary_key=True) text = models.CharField(db_column='Text', max_length=4000) datacode = models.IntegerField(db_column='DataCode') datasource = models.IntegerField(db_column='DataSource') starttime = models.DateTimeField(db_column='StartTime') kind = models.IntegerField(db_column='Kind') eventcategoryid = models.CharField(db_column='EventCategoryId',max_length=36, blank=True, null=True) class Meta: managed = True db_table = 'Event' I need an endpoint that returns only the first date and the last date in the database. The expected json response is: { "firstDate": "2019-03-02 12:02:11", "lastDate": "2019-08-02 10:55:01" } Can someone help me how I can get both value from starttime.