Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to change the display value in series using highcharts
(Notice: noticed stackoverflow didn't like me embeding pictures because the account is so new so I will post a link to them instead) I am quite new to stackoverflow, django and highcharts so I apologies for any inconvenience. So I am currently working with displaying time and dates in highcharts when I noticed a small problem. When looking at the chart everything looks fine like this. https://i.stack.imgur.com/6hALh.png But when I hover my mouse about a point on the chart it shows a different value. It looks like this https://i.stack.imgur.com/WUr2p.png I would like so that when focusing on a point it will display as HH:MM:SS like it does on the side instead of the total amount of microseconds. What do I need to change to make it happen? Here is the code for the chart <script> $(function () { $('#container').highcharts({ chart: { type: 'line' }, title: { text: 'Time worked by {{user_to_show}}' }, xAxis: { categories: {{dates|safe}} }, yAxis: [{ title: { text: '' }, gridLineWidth: 1, type: 'datetime', //y-axis will be in milliseconds dateTimeLabelFormats: { //force all formats to be hour:minute:second second: '%H:%M:%S', minute: '%H:%M:%S', hour: '%H:%M:%S', day: '%H:%M:%S', week: '%H:%M:%S', month: '%H:%M:%S', year: '%H:%M:%S' }, opposite: true }], plotOptions: … -
What languages & technologies are best for a community website development? [closed]
I'm seeking for some guidance for a solid start in a website project :) I'm a fresh CS graduate and currently want to try and build a community website that will include a few 'bulletin board' based pages, such as: Apartment rents Second handed furniture sales Classes, courses & private teachers Activities and so on... *The website will require a registration to use it. And all users can post their announcements. My questions are: What technologies should I use? maybe Django? What database would be considered best for this use? lets say for a few thousand users. Is there a designated design pattern for it? Do you have an idea what would be the best combination for this use? Thank You! -
Django Forms labels render next to field above FilteredSelectMultiple
I have added a widget 'FilteredSelectMultiple' into my sign up form and now the following label is next to the widget. How can I get the next field label to render after the widget? form.py class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') dbs_number = forms.CharField(max_length=13, label='DBS Number') hospitals = forms.ModelMultipleChoiceField(queryset=HospitalListModel.objects.all(), widget=FilteredSelectMultiple('HospitalListModel',False), required=False, ) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) template {% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <script type="text/javascript" src="{% url 'jsi18n' %}"></script> <button class="btn btn-success" type="submit">Sign Up</button> </form> {% endblock content %} -
How to routes in Django with Vue?
I want to create MPA with Vue for the frontend and Django for the backend. I only find a way to render the different routes via the Vue part. I made this with the vue create command. For example: App.vue <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/profile">Profile</router-link> This is just because I can't find the way to render my Vue pages from urls.py in my django application. For example, that's not my routes because I can't find how to write them: path('', TemplateView.as_view(template_name='index.html')), Can I render Vue pages in urls.py and how? -
Received unregistered task of type 'appname.tasks.add' - Celery
I'm trying to use Celery in my Django application. My tasks.py [this file is in the same folder as views.py] from celery import Celery app = Celery('tasks', backend='redis://localhost', broker='pyamqp://') @app.task def add(x, y): return x + y My views.py def view(): try: task = add.delay(4,5) except Exception as e: print (e) return True The error I am getting [2020-09-30 15:11:09,058: ERROR/MainProcess] Received unregistered task of type 'appname.tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. My settings.py [I have added celery in the installed apps] CELERY_IMPORTS = ( 'sweetapi.tasks' ) I use the following command to start celery celery -A tasks worker The same code is working when used on the python shell. Do I have to add more settings to make it work with the Django application? -
How do i get the value of a file field in Django session wizard view class
I am doing a project in which i am required to save the path of a file into a database. I am capturing the data using form-tools in Django as shown in the code below: class FormWizardView(SessionWizardView): template_name = "done.html" file_storage =DefaultStorage() #form_list = [Vacancy,Personal,Academic,Other] @property def __name__(self): return self.__class__.___name__ def get_context_data(self,form,**kwargs): user=self.request.user #print(vacancy) msg = Post_vacancy.objects.filter(end__gte=datetime.now().date()) u = User.objects.get(username=user) context=super(FormWizardView,self).get_context_data(form=form,**kwargs) context.update({'msg':msg,'u':u}) return context def get_form_step_files(self,form): return form.files def done(self, form_list,form_dict, **kwargs): user=self.request.user m= Applicant.objects.get(user=user) ad=self.kwargs['advert'] self.urlhash = id_generator() while Application.objects.filter(uid=self.urlhash).exists(): self.urlhash = id_generator() x=[form.cleaned_data for form in form_list] print(form_dict) #vacancy=x[0]['vacancy'] vacancy=Post_vacancy.objects.filter(advert=ad).values_list('subjects',flat=True)[0] tsc_no=x[0]['tsc_no'] duration=x[0]['duration'] uid=str(vacancy) + self.urlhash surname=x[1]['surname'] m_name=x[1]['m_name'] l_name=x[1]['l_name'] id_no=x[1]['id_no'] image_id=self.request.FILES['image_id']#x[1]['image_id'] institutionA=x[2]['institutionA'] award=x[2]['award'] kcse=x[2]['kcse'] image_cert=self.request.FILES['image_cert']#x[2]['image_cert'] image_certKC=self.request.FILES['image_certKC']#x[2]['image_certKC'] break_in=x[2]['break_in'] co_curriculum=x[3]['co_curriculum'] image_co=self.request.FILES['image_co']#x[3]['image_co'] leadership=x[3]['leadership'] image_lead=self.request.FILES['id_no']#x[3]['image_lead'] sex=m.gender All the other field data is being captured as expected except the image file field which return none. I have read elsewhere that i need to use request to capture these field but i dont know how. Any assistance will be highly appreciated Included here is the html snippet for the wizard view: <form action="" method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <div class="col-sm-3 form-control-label"> <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {% for i in form %} … -
How can i search in django like google search?
I want to implement search input in Django like google search,for example when i type word in input it gives the list of words below the input.i want to implement auto search in Django. -
How to pass object properties from view to template in Django?
I must be missing something really basic here. I have created an object in my view to pass to my template. All the properties of my object are passed successfully but the last property, an integer, is not shown when rendering my template. Why? Here is my code: Views.py: def courseListView(request): object_list = {} courses = Course.objects.all() for course in courses: object_list[course] = { 'title': course.title, 'slug': course.slug, 'thumbnail': course.thumbnail, 'get_absolute_url': '/' + course.slug, 'progress': int(lessonsCompleted.objects.filter(user=request.user.id, course=course.id).count() / course.lessons.count() * 100) } print(object_list) context = { 'object_list': object_list, } return render(request, "courses/course_list.html", context) This way I am creating an object that looks like this when I print it: {<Course: Mezclar música chill y ambient>: {'title': 'Mezclar música chill y ambient', 'slug': 'mezcla-chill-ambient', 'thumbnail': <ImageFieldFile: mixing.jpeg>, 'get_absolute_url': '/mezcla-chill-ambient', 'progress': 66}, <Course: Componer bases electrónicas>: {'title': 'Componer bases electrónicas', 'slug': 'componer-bases-electronicas', 'thumbnail': <ImageFieldFile: beats.jpeg>, 'get_absolute_url': '/componer-bases-electronicas', 'progress': 75}, <Course: Melodías ultrasónicas>: {'title': 'Melodías ultrasónicas', 'slug': 'melodias-ultrasonicas', 'thumbnail': <ImageFieldFile: melodies.jpeg>, 'get_absolute_url': '/melodias-ultrasonicas', 'progress': 50}} Ultimately I want to pass to the template the progress for each course, for the currently logged user, so I can show this information for each course in my web page. To show that, in my template I am … -
Django JSONField with default and custom encoder
Django version: 3.1.0, MySQL backend I have a JSONField on my model: class Employee(models.Model): address = models.JSONField( encoder=AddressEncoder, dedocer=AddressDecoder, default=address_default ) Then the encoder looks like this: class AddressEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, Address): return dataclasses.asdict(o) raise TypeError("An Address instance is required, got an {0}".format(type(o))) Then the address_default looks like this: def address_default(): encoder = AddressEncoder() address = Addres(...) return encoder.encode(address) Currently I have set the address_default to return a dict. Although it should actually return an Address instance. When I change this so that the address_default returns an instance of Address, an error is raised TypeError: Object of type Address is not JSON serializable. However, in other parts of the code where the address is in fact an instance of Address, no errors are raised. So the custom AddressEncoder does not seem to be used on the value provided by the address_default. When the address attribute on Employee is set to e.g. a string, no error is thrown. This might have to do with what is explained in Why is Django not using my custom encoder class. The code in AddressEncoder is not executed. Question: What is the correct way to set up the address_default, and Encoder/Decoder so … -
How do I specify urlconf correctly in Django reverse() function?
I need to specify my file containing the URLs explicitly like this: link = reverse(link, urlconf='backend/urls') The backend folder is located in a src folder of the project. But the path 'backend/urls is not found, I get an error: No module named 'backend/urls' How do I specify the path correctly? I'm not sure where Django thinks the root of the project is. -
ELI5: Django Migrations - Do they change the SQL database?
My company has tasked me with creating a small proof-of-concept web app where we would like to read and display a few columns from one of our tables in our microsoft sql server. I have setup my django project and installed the django-mssql-backend etc. However I found the explanation of migrations rather vague Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into. Django migrations documentation I'm not allowed to alter the database in any way as it would break some legacy systems so I want to make sure that migrating does not alter the database. Thus my question is rather simple, would executing the "python manage.py migrate" alter the database or is it only locally in my django project? -
Django, get fullpath of loaded file
/django 3/ I want to use my loaded file , with external script to do that I need full path for this file in my media folder, each time I am loading same named file, I get unique name. example: input : image12.jpg in folder media -> image12_0x982.jpg my model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) #I have also prepared forms.py but its simillar as model form my views.py: from model import InJPG def get_name(request): file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() if file2.is_valid(): file2.save() #print file path: file = InJPG.objects.all() for f in file: print(f.file_name) return render(request,'my.html',{'file1':file1,'file2':file2}) In this last line, I am receiving list of all files with right paths with unique names. How to get only paths for file1 and file2 ? And open those files using external script? -
Django LocaleMiddleware only works for LANGUAGE_CODE language
My goal is to have the following: www.example.com/en provides an English website www.example.com/de provides a German website I am using Django 3.1 for this. My settings.py contains the following: LANGUAGE_CODE = 'en' prefix_default_language=True TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en','English'), ('de', 'German') ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'templates/locale'), ) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] My root urls.py contains the following: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('mainpage.urls', namespace='mainpage')), ) If I visit www.example.com/en it works, if I visit www.example.com/de I get a 404 error. If I now change LANGUAGE_CODE = 'en' to LANGUAGE_CODE = 'de' www.example.com/de will work but www.example.com/en will give me a 404 error. How can I fix this, so that it works for both? I think it should not depend on LANGUAGE_CODE, should it? -
how to get the sum of a field after apply filter by django filter search?
would you please help me, I want to get the sum of a field after applying django filter search. for example I want to acheive the total of apartment's after filter View.py @login_required(login_url='loginPage') @allowed_users(allowed_roles=['admin']) def building(request): fltr_bld = FilterBuilding(request.GET, queryset=Building.objects.all()) apts=Building.objects.all().aggregate(Sum('total_apt')).get('total_apt__sum', 0) return render(request, 'building.html', {'fltr_bld': fltr_bld, 'apts':apts}) Filter.py class FilterBuilding(django_filters.FilterSet): start_date = DateFilter(field_name='date_created', lookup_expr='gte') end_date = DateFilter(field_name='date_created', lookup_expr='lte') name = CharFilter(field_name='name', lookup_expr='icontains') desc = CharFilter(field_name='desc', lookup_expr='icontains', label='Descriptions') class Meta: model = Building fields = ['name', 'total_apt', 'desc', 'end_date', 'start_date'] exclude = ['other_details'] -
Generic detail view View must be called with either an object pk or a slug in the URLconf
how to access foreign key in urls.py? ################models.py ... class Category(models.Model): title = models.CharField(verbose_name='TITLE', max_length=200) slug = models.SlugField('SLUG', unique=True, allow_unicode=True, help_text='one word for title alias.') ... def __str__(self): return self.title class Episode(models.Model): category = models.ForeignKey("Category", verbose_name=("CATEGORY"), on_delete=models.CASCADE) number = models.IntegerField(). ... meta: ... def __str__(self): ... def get_absolute_url(self): return reverse("manga:episode_detail", kwargs={"slug": self.category.slug, "number": self.number}) #####################urls.py ... # path('category/<slug:category.slug>/<int:number>', views.EpisodeDetailView.as_view(), name="episode_detail"), ] #################views.py ... class EpisodeDetailView(DetailView): model = Episode template_name = 'manga/episode_detail.html' context_object_name = 'episode' ** **It throwed `Generic detail view EpisodeDetailView must be called with either an object pk or a slug in the URLconf.`** I wanna see Detail of Episode. but I couldn't... I've tried throw queryset, but it doesn't work... how to access foreign key in urls.py? ** # def get_queryset(self): # return Episode.objects.filter(category__slug=self.kwargs['lab']) def get_queryset(self): employee = Category.objects.get(slug=self.kwargs['slug']) print(employee) return Episode.objects.get(category=employee, number=self.kwargs['number']) -
Adding files to form in Django makes editing form behave differently - why?
I have a simple model I can edit by using another simple form - and that works well, while clicking "edit" it correctly shows existing fields in an editing form; everything changes when I add files=request.FILES to my view - then it somehow forgets existing data and I'm left with clear form and info "This field is required" on required fields (even though they are filled because this item exists) views.py def add_news(request): if request.method == 'POST': news = NewsModel(author=request.user) form = AddNewsForm(instance=news, data=request.POST, files=request.FILES) #this works fine if form.is_valid(): form.save() messages.success(request, 'Added a news!') return redirect('main:news') else: messages.warning(request, "You didn't fill the form, try again") else: form = AddNewsForm() return render(request, 'news/add_news.html', {'form':form}) def edit_news(request, id): news = get_object_or_404(NewsModel, id=id) form = AddNewsForm(request.POST or None, instance=news, files=request.FILES) #here is the problem if request.POST and form.is_valid(): form.save() messages.success(request, 'Changed a news.') return render(request, 'news/add_news.html', {'form': form}) urls.py re_path(r'^news/new/$', views.add_news, {}, 'news_new'), re_path(r'^news/edit_(?P<id>\d+)/$', views.edit_news, {}, 'news_edit'), forms.py class AddNewsForm(forms.ModelForm): class Meta: model = NewsModel fields = '__all__' template <h1> Add/change a news</h1> <form method="POST" enctype="multipart/form-data"> {{form}} {% csrf_token %} <h2> <input type="submit" value="Go!"/> </h2> </form> Without that one files=request.FILES in edit_news, everything works. What's going on? -
Django formset factory and Crispy forms
I'm trying to apply formset helpers to my template and can't figure out where I'm wrong. I have implemented a function in javascript to dynamically add subjects. I am a beginner with formsets, any help would be great! Thanks !!! forms.py I create the form and the form helper : class NuovoSoggetoCsForm(ModelForm): class Meta: model = Soggetto fields = [ 'data_ora_creazione', 'tipologia_soggetto', 'cognome', 'nome', 'sesso', 'data_nascita', 'comune_nascita', 'provincia_nascita', 'stato_nascita', 'comune_residenza', 'localita_residenza', 'provincia_residenza', 'tipo_documento1', 'ente_riascio_doc1', 'numero_documento1', 'telefono1', 'mail_pec', 'foto_documento1' ] class SoggettoFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = Layout( 'data_ora_creazione', 'tipologia_soggetto', 'cognome', 'nome', 'sesso', 'data_nascita', 'comune_nascita', 'provincia_nascita', 'stato_nascita', 'comune_residenza', 'localita_residenza', 'provincia_residenza', 'tipo_documento1', 'ente_riascio_doc1', 'numero_documento1', 'telefono1', 'mail_pec', 'foto_documento1', ) self.render_required_fields = True views.py I create the formset and helper in the view : .....some code..... SoggettoFormset = formset_factory(NuovoSoggetoCsForm, extra=0, can_delete=True) helper = SoggettoFormSetHelper() .....some code..... return render(request, 'soggetto.html', {'formset_soggetto' : formset_soggetto, 'helper' : helper }) soggetto.html I create the template with dynamic addition : ....some code..... <fieldset> {{ formset_soggetto.management_form }} <div id="formset_wrapper_soggetto" style="background-color:#f2f2f2;"> {% for form_soggetto in formset_soggetto.forms %} <div class='table'> <table class='no_error'> {% crispy form_soggetto.as_table helper %} </table> </div> {% endfor %} </div> <div id="emptyform_wrapper_soggetto" style="display: none"> <legend>Soggetto</legend> <div class='table'> <table class='no_error'> {{ formset_soggetto.empty_form.as_table }} </table> </div> </div> </fieldset> … -
I want to limit file size upload below 5 mb before uploading
I am trying to check file size upload in jinja2 template in django. I want to check it before it gets uploaded, the code below is a form which will be submitted after clicking the button. It will upload a dataset in browser. <form method="POST" class="post-form" enctype="multipart/form-data"> {{ form.as_p }} <button onclick="onSubmitBtn()" type="submit" id="btn-hide" class="btn btn-danger">Upload</button> </form> -
PyInstaller with django and django-extensions
I'm trying to build executable with django using PyInstaller and used django-extensions library to use 'runserver_plus'. Using, django==1.11 PyInstaller==3.4 django-extensions==2.2.1 Added in settings.py file, INSTALLED_APPS = ( ... 'django_extensions', ) In PyInstaller loader file for django, PyInstaller\loader\rthooks\pyi_rth_django.py import django.core.management import django.utils.autoreload def _get_commands(): # Django groupss commands by app. # This returns static dict() as it is for django 1.8 and the default project. commands = { 'changepassword': 'django.contrib.auth', 'check': 'django.core', 'clearsessions': 'django.contrib.sessions', 'collectstatic': 'django.contrib.staticfiles', 'compilemessages': 'django.core', 'createcachetable': 'django.core', 'createsuperuser': 'django.contrib.auth', 'dbshell': 'django.core', 'diffsettings': 'django.core', 'dumpdata': 'django.core', 'findstatic': 'django.contrib.staticfiles', 'flush': 'django.core', 'inspectdb': 'django.core', 'loaddata': 'django.core', 'makemessages': 'django.core', 'makemigrations': 'django.core', 'migrate': 'django.core', 'runfcgi': 'django.core', 'runserver': 'django.core', 'runserver_plus':'django_extensions', 'shell': 'django.core', 'showmigrations': 'django.core', 'sql': 'django.core', 'sqlall': 'django.core', 'sqlclear': 'django.core', 'sqlcustom': 'django.core', 'sqldropindexes': 'django.core', 'sqlflush': 'django.core', 'sqlindexes': 'django.core', 'sqlmigrate': 'django.core', 'sqlsequencereset': 'django.core', 'squashmigrations': 'django.core', 'startapp': 'django.core', 'startproject': 'django.core', 'syncdb': 'django.core', 'test': 'django.core', 'testserver': 'django.core', 'validate': 'django.core' } return commands After creating executable for django project. Where as, 'runserver' works smoothly. Not able to use 'runserver_plus' command after building executable with PyInstaller. ubuntu@ubuntu:~/executables$ ./dist/myproject/myproject runserver_plus * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit) * Restarting with stat Unknown command: '/home/ubuntu/executables/dist/myproject/myproject' Type 'myproject help' for usage. ubuntu@ubuntu:~/executables$ After executing, ubuntu@ubuntu:~/executables$ ./dist/myproject/myproject help Type 'myproject help <subcommand>' … -
How to validate form by getting exact value on integer field
I am new in Django, I am trying to validate a form to get the particular value, if value is not exact validate error. For example, i have a field in a model (cot_code), the field has a integer value (12345). I have created a form for this field, i want if the user enter 12345 in form, the form will be valid as success "code is correct", but when user enter a wrong code (55777) the form will raise a validator error "Wrong code". I do not know how to go on with the views. Model: class CotCode(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cot_code = models.IntegerField(default='0', blank=True) # I have set this field as 12345 in model. date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'CotCode' verbose_name_plural = 'CotCode' ordering = ['-date'] def __str__(self): return self.user.username Forms: class CotCodeForm(forms.ModelForm): class Meta: model = CotCode fields = ('cot_code',) Views: @login_required def TransferCOTView(request): #Don't know how to go on here return render(request, 'transfer_cotcode.html') Template: <form method="POST" action="" class="text-center needs-validation" novalidate> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default">C.O.T</span> </div> <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default" placeholder="Enter your COT Code" required> <div class="invalid-feedback"> Please enter your C.O.T code. </div> </div> … -
Why is gettext giving me automatically incorrect translations?
I am using gettext translations for my Django project and I keep adding to the .po file new and new translations by makemessages and compilemessages. What is happening now is that when I make messages then I check the .po file and there many of the strings have been automatically translated, although this is 100% unique string. example: Now generated: #: .\agregator\models.py:1855 #, fuzzy #| msgid "Distribution order" msgid "Distribution Product Parameters" msgstr "Objednávka u distribuce" it automatically translated according to the msgid "Distribution order" that is not any close to the actual string neither there is any link to this msgid. Can anyone explain to me what is happening in the background and how can I remove all such links so for msgstr I get only empty strings, (unless the strings are 100% similar)? Thank you in advance. -
How to keep Database entries on Server after git pull working with Django?
Everytime i pull the new Version of my Django app on my Server it doesnt keep the entries that i made. It only keeps the entries i made on my local Version. So all entries i did on my server are lost. Is there a way to keep the entries. I work with postgressql. So i tried to google the problem, but i couldnt find any solution to my problem. I work with digitalocean and ubuntu on the server. I dont think that it does matter but i want to give as much information as possible. Can i save the database or do i need to do anything completely different. I hope that you can help me figure this out. -
How can I go from my javascript to views.py of another app from present app
My javascript: xhttp.open('POST', 'avgsize/avgpython' ,true); xhttp.setRequestHeader("content-type","application/json"); xhttp.send(JSON.stringify(dates)); xhttp.onreadystatechange=function(){ if(this.readyState==4 && this.status==200){ alert(this.responseText); } } My present Home app(all urls am visiting are working from this app ) urls.py: urlpatterns = [ path('' , views.HomeBase , name="HomeBase"), path('Home' , views.Home , name="Home"), path('astroids' , include('Astroids.urls')), path('nearest' , include('Nearest.urls')), path('fastest' , include('Fastest.urls')), path('avgsize/' , include('Avgsize.urls')), ] My Avgsize app urls(i want to come here from Home app): path('avgpython' , views.avgpython , name="averagesizePython"), what changes should i make in the code so that i can go from javascript to Avgsize app and link avgpython and get access to views.avgpython. Please Help...!! -
Django prepends url name to imagefield location, causing 404
Everything was working fine and images were loading. from model: image = models.ImageField(upload_to='static/images/bin_sheet/', default='static/images/bin_sheet/no-img.jpg') from urls.py path('bin_sheet/', views.IndexView.as_view(), name='bin_sheet'), from views.py: class IndexView(generic.ListView): template_name = 'bin_sheet.html' context_object_name = 'bin_list' from template: <img class="card-img-top" src="{{ bin.image }}" alt="no image"> from html souce in rendered html: <img class="card-img-top" src="static/images/bin_sheet/sb_HAm6pem.jpg" alt="no image"> from django terminal output: Not Found: /bin_sheet/static/images/bin_sheet/sb_HAm6pem.jpg "GET /bin_sheet/static/images/bin_sheet/sb_HAm6pem.jpg HTTP/1.1" 404 3324 It's adding /bin_sheet/ now. If I enter in that address minus the bin sheet then it loads the image. wtf would cause django to add bin_sheet? The page has the correct location but django tries to load if from a non existent location. -
How to Get the exact address location like google map tracker with python/django
I've tried to get the location by ip address..but result is wrong.. import requests res = requests.get("https://ipinfo.io/") data = res.json() print(data) I want to know location like this: Food panda Location Tracker Google location Tracker