Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Media image files not loading on production on apache
After uploading image by user its not showing on listing page, but its saving in media folder in my production, but its working fine for development. I configured MEDIA_URL, MEDIA_ROOT in settings.py and urls.py and also set alias in apache but still its not loading image In settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' In urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) In Apache(/etc/apache2/sites-available/000-default.conf) <VirtualHost *:80> <Directory /var/www/html/ourdemocracy/newproject/newproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess newproject python-path=/var/www/html/ourdemocracy/newproject python-home=/var/www/html/ourdemocracy/venv WSGIProcessGroup newproject WSGIScriptAlias / /var/www/html/ourdemocracy/newproject/newproject/wsgi.py Alias /static /var/www/html/ourdemocracy/newproject/static <Directory /var/www/html/ourdemocracy/newproject/static> Require all granted </Directory> Alias /media /var/www/html/ourdemocracy/newproject/media/> <Directory /var/www/html/ourdemocracy/newproject/media/> Require all granted </Directory> </VirtualHost> On listing page {% if campaign.campaign_image %} <img src="{{ MEDIA_URL }} {{ campaign.campaign_image.url }}" alt="{{ campaign.title }}"> {% else %} <img src="{% static "img/cause-6.jpg" %}" alt=""> {%endif%} when i am locating the media image its showing following error The requested URL /media/campaigns/images/myimage.jpg was not found on this server. -
Roles in django model
I have a model in django, in which there will be several roles - regular user, admin and manager. Each of them will be able to do something else. Is the following model OK to work correctly? class Team(models.Model): name = models.CharField('Name', max_length=128) users = models.ManyToManyField(User) admins = models.ManyToManyField(User) managers = models.ManyToManyField(User) def __str__(self): return self.name -
project does not recognize custom filter templatetags when deploying(Django + uwsgi + nginx )
When a personal project is deployed to a ubuntu server (16.04), the command ( python manage.py runserver 0.0.0.0:8000) can be used to access the project on the web page, but the static file is not loaded. However, when running with the (uwigs) command, the error was reported to be inaccessible. Project Description:(django2.1,python3) filter positionsetting contentUwsgi+nginx configuration When I run the command in Xshell: use runserver use uwsgi I have used some methods, but I still can't.Another error occurred using the uwsgi command: use uwsgi I don't know if I am clear about it, thank you for your help. -
Player-Team model relationship
I am building a database to show the tournaments of online games. I have three questions; first one, Which method should i use class Player(models.Model): team=models.ForeignKey(Team,related_name='player',verbose_name='Team') OR class Team(models.Model): player=models.ManyToManyField(Player) third; my tables between the team and the player does this look correct? Last; After these tables I will make the tables between the match and the tournament. What should be the relationship between the match and the team class OnlineGame(models.Model): game_name=models.CharField(max_length=120) class Team(models.Model): name=models.CharField(max_length=255,verbose_name="Takım ismi") slug=models.SlugField(max_length=120,unique=True) bio=models.TextField() country=models.CharField(max_length=50) logo=models.ImageField(null=True,blank=True,upload_to='team') background=models.ImageField(null=True,blank=True,upload_to='team') extra=models.CharField(null=True,blank=True,max_length=150) website=models.CharField(null=True,blank=True,max_length=120) game=models.ManyToManyField(OnlineGame)#manytomany because team have one or more online game team (for example sk gaming have lol and counter-strike team def get_unique_slug(self): slug=slugify(self.name.replace('ı','i')) unique_slug=slug counter=1 while Team.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def __str__(self): return self.team_name class PlayerGameRole(models.Model): role=models.CharField(max_length=50) class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) nickname=models.CharField(max_length=120) first_name=models.CharField(max_length=120) last_name=models.CharField(max_length=50) birthday=models.DateField(null=True,blank=True) picture=models.ImageField(null=True,blank=True,upload_to='player') country=models.CharField(max_length=50) role=models.ManyToManyField(PlayerGameRole) team=models.ForeignKey(Team,related_name='player',verbose_name='Team') twitch=models.URLField(null=True,blank=True) facebook=models.URLField(null=True,blank=True) twitter=models.URLField(null=True,blank=True) extra=models.CharField(max_length=150) game=models.ManyToManyField(Game) def get_unique_slug(self): slug=slugify(self.nickname.replace('ı','i')) unique_slug=slug counter=1 while Player.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def age(self): import datetime return int((datetime.date.today() - self.birthday).days / 365.25) -
How to run tests in a django view without affecting the database
I am trying to run the functional tests (using Selenium in python/django) directly from the django views by using management.call_command, in order to allow the user to run the test from the web site. The django view is something like: class MyView(): def get(self): output = call_command('test', 'folder.tests.MyTest') # doing ./manage.py test folder.tests.MyTest test_result = 'Test result: ' + output return something_http_with_test_result What is the best way to do this in order to do not affect the current user data? MyTest is going to create a lot of object in the database but the user must not see them. Thank you -
Work of FormView with Ajax request is not clear
I try to send data from the form to the server using post ajax request. But for some reason, neither form_valid nor form_invalid works. But comes in post method. I try to pull out the form from request.POST, but it turns out to be invalid. forms class CreditFilterExtendedForm(forms.Form): sum2 = forms.CharField(widget=forms.NumberInput(attrs={'id': "sum2", 'class':"form-control"})) views class CreditsList(ListView): def get(self, request, *args, **kwargs): big_form = CreditFilterExtendedForm(self.request.GET or None, prefix="big") class BigFormView(FormView, CreditsList): form_class = CreditFilterExtendedForm prefix = 'big' def form_valid(self, form, *args, **kwargs): print(1) def form_invalid(self, form, *args, **kwargs): print(2) def post(self, *args, **kwargs): print(3) template <form action="{% url 'big_form' %}" class="mt-3" id="big_form"> {% csrf_token %} {{ big_form.sum2 }} <button type="submit" name="{{ big_form.prefix }}">Submit</button> </form> $(document).on("submit", "#big_form", function (e) { e.preventDefault(); $form = $(this); var form_data = new FormData($form[0]); $.ajax({ type: 'post', url: '{% url "big_form" %}', data: form_data, processData: false, contentType: false, success: function(data) { } }) }) There are 2 questions: Why first comes into the post method? Although there is a similar form and it comes right into form_valid. How to find out why the form is invalid? All fields are filled. -
django.core.exceptions.ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module
I have an almost fresh install of django and when I try to python manage.py runserver.It is is giving me this error: File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\my2\lib\site-packages\django\core\servers\basehttp.py", line 50, in ge t_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. settings.py INSTALLED_APPS = [ 'cognitive.apps.CognitiveConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jchart', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' WSGI_APPLICATION = 'myproject.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() ```**strong text** -
Form Not Submitting after using slug in my model
I am working on a project, where I need to hide the primary key in the url so I implemented slug in all my models. But the model which is using the foreign key to another model does not seem to work properly. The form is taking values but is not getting submitted no matter what I do. I don't know what is wrong in my code. views.py class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): self.object = form.save(commit=False) self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0] self.object.save() return HttpResponseRedirect(self.get_success_url()) models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) def __str__(self): return self.user.username def get_absolute_url(self): if (self.verified==True): return reverse("NewApp:mail", kwargs={'pk': self.pk}) else: return reverse("NewApp:userlist") class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("index") template <form method="POST"> {% csrf_token %} <div class="form-group col col-md-3"> <label>Centre Name</label> {{form.centre_name}} </div> <label … -
Multiple models inlineformset django
I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store) A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User") The second is "Product" that has as foreignKey the "ProductPlace" model The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model I created formsets associated to these three models in the "forms.py" file. But i don't know how to do for "views.py" #models.py from django.db import models from django.core.validators import FileExtensionValidator from .validators import validate_file_extension from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class ProductPlace(models.Model): name = models.CharField(max_length=50) num_road = models.IntegerField(blank=False, null=False) name_road = models.CharField(max_length=50) postal_code = models.IntegerField(blank=False, null=False) city = models.CharField(max_length=50) country = models.CharField(max_length=50) acquired_by = models.ForeignKey(User, related_name="product_places", null=True, on_delete=models.SET_NULL) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(blank=False, null=False) place = models.ForeignKey(ProductPlace,related_name="products", on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name class Menu(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(blank=False, null=False) place = models.ForeignKey(ProductPlace, related_name="menus", on_delete=models.CASCADE) … -
Stop signal send trigger for specific Sender
I'm using Django 2.2 In my application, there is a shared user feature and every shared user are added to User model with is_shared field set to True. The shared user is linked to a user in SharedUser model like class SharedUser(models.Model) user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='owner_user') shared_user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='shared_user') On delete of a record from SharedUser model, I also have to delete the linked shared_user record from the User model. For that I'm using the post_signal receiver. receivers.py @receiver(post_delete, sender=SharedUser, dispatch_uid='post_delete_shared_user') def post_delete_shared_user(sender, instance, *args, **kwargs): try: if instance and instance.shared_user: owner = instance.user instance.shared_user.delete() except: pass and the receiver is loaded in the app.py config class SharedUsersConfig(AppConfig): name = 'shared_users' def ready(self): from . import receivers Now, whenever a record from the SharedUser model is deleted, it makes a lot of SQL queries. When the import receivers is removed from the apps.py file. There are a lot more SQL queries being made when the receiver is used to delete the associated user. In my use case, there is nowhere the shared_user is associated to any other model other than SharedUser model. How can I reduce the query on deleting a user? Can I disable sending the … -
How can i remove this django server error
I'm getting this error when i am using the command: python manage.py runserver Error:[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions -
multiple annotates are not working properly
Using multiple annotate queries giving unexpected results. When I use annotate separately, it works fine. event_queryset = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter), sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30), rating = Cast(F('sales')/F('days'), FloatField(2))) or event_queryset = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter)).annotate(sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30)).annotate(rating = Cast(F('sales')/F('days'), FloatField(2))) In both queries, days variable is giving wrong values for some items. Sales is fine. And if I do this: event_queryset_days = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter)) event_queryset_sales = OrderItemTable.objects.annotate(sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30) Both give correct values. Can anyone tell what I am doing wrong. Or how can calculate rating if I use separate queries for days and sales. -
Unable to run background tasks with Celery + Django + Gunicorn
Stack: Python v2.7 Django v1.11 Celery v4.3.0 Gunicorn v19.7.1 Nginx When I try to run django server and celery manually the async tasks executes as expected. The problem comes when I am deploying django project using Gunicorn plus Nginx. I tried running Celery using supervisor but it didn't help. views.py def _functionA(): _functionB.delay() #where _functionB is registered async task. settings.py # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' gunicorn.service [Unit] Description=Gunicorn application server.... After=network.target [Service] User=root Group=www-data WorkingDirectory=<myprojectdir> Environment=PYTHONPATH=<ENV> ExecStart=<myprojectdir>/env/bin/gunicorn --workers 3 --access-logfile access_gunicorn.log --error-logfile error_gunicorn.log --capture-output --log-level debug --bind unix:<myprojectdir>/myproject.sock <myproject>.wsgi:application [Install] WantedBy=multi-user.target myproject_nginx.conf server { listen 8001; location / { include proxy_params; proxy_pass http://unix:<myprojectdir>/myproject.sock; } } celery worker celery worker -B -l info -A myproject -Q celery,queue1,queue2,queue3 -n beat.%h -c 1 Can anyone help me with my question(s) below: Why is that when Django is deployed using Gunicorn and nginx the Celery worker doesn't executes tasks whereas when ran manually it is able to execute the tasks i.e. when ran with python manage.py runserver ... . -
Custom validation and saving of django inline forms
I am trying to represent a base model which has some attributes that change over time. I have gotten the model definitions pretty set in stone -- most of this code just enforces that there can be no overlaps between DatedModelState instances on any given BaseModel instance. class DatedModelState(models.Model): id = models.AutoField(primary_key=True) base_model = models.ForeignKey(BaseModel, related_name='dated_states', on_delete=models.CASCADE) begin_date = models.DateField() end_date = models.DateField() def clean(self, *args, **kwargs): super().clean(*args, **kwargs) other_dated_states = self.base_model.dated_states.exclude(id=self.id) # Code omitted, but validate that there are no date overlaps with any other DatedModelStates... To interact with this through the admin console, I am using an admin.TabularInline together with a base ModelAdmin. class DatedResourceStateInline(admin.TabularInline): model = models.DatedResourceState extra = 0 # Do not show extra 'empty' records @admin.register(models.BaseModel) class BaseModelAdmin(admin.ModelAdmin): list_display = (...) fields = (...) inlines = [DatedResourceStateInline] My issue comes when I try to save the ModelAdmin form, including all inline DatedResourceState forms, where I have changed a start/end date in more than one DatedResourceState. A quick and dirty example... Current State id begin_date end_date 1 - 2019-07-05 -> 2019-07-06 2 - 2019-07-06 -> 2019-07-20 If I try to move the boundary one day later, my validations fail Attempted State id begin_date end_date 1 - … -
How can I run functional tests from a django view?
I would like to run the functional tests in the webpage using python,django. Can't I just use management.call_command like this in my views.py ? call_command('test', 'folder.tests.Mytest') Mytest inherits from TestCase of Selenium and contains the classic setUp() and test_() methods. Here the error shown is: "ValueError: signal only works in main thread" Cannot the command be called from the views? Thank you -
Error in Django email validation in model forms(signup)
I am trying to validate the email of the signup form if the user with that email already exists it should show an error like email already exists but I am not able to achieve this with the below code forms.py from django.forms import ModelForm from django import forms from . models import signup class signupForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = signup fields = ['username', 'email' , 'password','confirm_password'] def clean(self): cleaned_data = super(signupForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) email = self.cleaned_data.get('email') try: match = signup.objects.get(email=email) print(match) except signup.DoesNotExist: # Unable to find a user, this is fine return email # A user was found with this as a username, raise an error. raise forms.ValidationError('This email address is already in use.') class loginForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = signup fields = ['email','password'] it is showing AttributeError at /signup 'str' object has no attribute 'get' this error -
django form not submitting due to slug and foreign key
My django cabin form is not submitting. I have applied foreign key and slug in my cabin's model and after that my form stopped getting submitted. whenever I enter all the fields and hit submit button,the form page is getting reloaded and no data is getting submitted.Most Importantly it is not showing any error so that I can fix it.I have tried and searched a lot about it and tried different things but still it didn't work. I am stuck to it. Please help!! class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) class Cabin(models.Model): random_string = str(random.randint(100000, 999999)) centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE,blank=True,null=True) code = models.CharField(max_length=6, blank=False, unique=True, default=random_string) total_seats = models.IntegerField(blank='False') category=models.CharField(max_length=100, default=False) booked_date=models.DateField(blank='False') released_date=models.DateField(blank='False') price=models.IntegerField(blank=False, default=None) slug = models.SlugField(unique=False,default=None) def save(self, *args, **kwargs): self.slug = slugify(self.category) super(Cabin, self).save(*args, **kwargs) In views.py file class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): self.object = form.save(commit=False) self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0] … -
No module found at django deployment (apache,wsgi)
I have deployed a small django application, and I want to display a graph on a page. For the realization of graphs in python I use the plotly library. In production, the import of plotly worked very well, no worries. But when deploying django with apache2 and wsgi, there is an import problem that the plotly module is not found, I don't know how to do that for several hours now. If some have already encountered this kind of problems.... thank you for your feedback -
TypeError: 'NoneType' object is not callable - Beautifulsoup 4
I'm trying to save the scraped data in the Postgres database. I want to use django models for this. I tried to use the Psycopg2 package before, but I found out that it is unnecessary so I decided to use just django models. the data did not go to the database also when I used the Psycopg2 package. I get this error: Traceback (most recent call last): File "/home/xxxx/Desktop/project/django/tnapp/scrap.py", line 61, in <module> scraped_author = author(name='author name') TypeError: 'NoneType' object is not callable Scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome(ChromeDriverManager().install()) contents = [] authors = [] for article in all_links: d.get(article) … -
Overriding Django Save and returning id if exists
I am using Django_rest framework to upload files to my site. However, often I am uploading the same file, so I wish to avoid uploading the same file multiple times. To overcome saving multiple copies of the same file, I have overwritten the save model to upload a file and delete the file if it already exists. This works although I feel it is alot of not needed uploading. However, I can't get the existing id to be returned from my serialiser to not do this. is there a better solution to this? Model.py class IMAGES(models.Model): IMAGE = models.FileField(max_length=150,upload_to='documents/%Y/%m/%d') def __unicode__(self): return str(self.id) def save(self, *args, **kwargs): imstring="documents/" + datetime.now().strftime('%Y') + "/" + datetime.now().strftime('%m') + "/" + datetime.now().strftime('%d') + "/" + str(self.IMAGE) try: this = IMAGES.objects.filter(IMAGE=imstring)[0] # This sees if the filename is already in the database. if this.IMAGE: # if it is, # delete the file and replace it. os.remove(this.IMAGE.path) except IndexError: pass except ObjectDoesNotExist: pass super(IMAGES, self).save(*args, **kwargs) serializer.py class IMAGESEntrySerializer(serializers.ModelSerializer): class Meta: model = IMAGES fields = ( 'id', 'IMAGE') def create(self, validated_data): result, other = IMAGES.objects.get_or_create(**validated_data) return result def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.NAME … -
How to load jquery properties to extended template from base template, jquery included in base template
i want to get jquery propertys from base template to extended template headerfooter.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" href="{% static 'medicure/images/favicon.png' %}" type="image/png" /> <title>Medicure</title> <!-- Bootstrap --> <link href="{% static 'medicure/css/bootstrap.min.css' %}" rel="stylesheet"> {% block headerfooter %} {% endblock %} <script src="{% static 'medicure/js/jquery.min.js' %}"></script> <!-- Bootstrap --> <script src="{% static 'medicure/js/bootstrap.min.js' %}"> </script> <!-- FastClick --> <script src="{% static 'medicure/js/fastclick.js' %}"></script> <!-- NProgress --> <script src="{% static 'medicure/js/nprogress.js' %}"></script> company.html {% extends "headerfooter.html" %} {% load staticfiles %} {% block headerfooter %} <script src="{% static 'masters/js/masters.js' %}"></script> {% endblock %} in the above example i have included jquery in headerfooter.html, and i have included masters.js file in company.html, in master.js javascript is working and jquery is not working, if i include below script on top of masters.js then jquery is working fine, so i need to include jquery on every page even it is extended. <script src="{% static 'medicure/js/jquery.min.js' %}"></script> -
How can i get a object from a other function in django
I have two functions projectTimerStart to start the timer and projectTimerStop i want to use the object which is created in projectTimerStart and i want to end the time when projectTimerStop , and this should be saved in a database ps: Both the functions are not in class they are normal functions enter code here def projectTimerStart(request, slug): project_detail = Project.objects.get(slug=slug) b = ProjectTimer(time_started=datetime.now(), working_project=project_detail, working_freelancer=request.user ) b.save() return HttpResponseRedirect(reverse('project_timer', kwargs= {"slug":slug})) def projectTimerStop(request, slug): project_detail = Project.objects.get(slug=slug) #i want something here super method or something return HttpResponseRedirect(reverse('project_timer', kwargs= {"slug": slug})) -
Need guide lines or hints to use `graphene-python + django_filters` query on `JSONField`?
I am practicing GraphQL because it offs load backend burden a lot comparing to django-restframework in some use cases. Here is my models.py from django.contrib.postgres.fields import JSONField from django.db import models class Fauzan(models.Model): name = JSONField() schemas.py import graphene from graphene_django import DjangoObjectType from fauzans.models import Fauzan class FauzanObjectType(DjangoObjectType): class Meta: model = Fauzan class Query(graphene.ObjectType): fauzans = graphene.List(FauzanObjectType) def resolve_fauzans(self, info): return Fauzan.objects.all() schema = graphene.Schema(query=Query) With limited documents. I can not imagine what is the the implementation of search, filter according to django_filters How do I do search, filter over the JSONField using django_filters? -
How to set up free SSL certificate for my site running on google cloud plateform. (Windows 10)
I have hosted my website on google cloud platform on a windows server(newbie). Buyed domain from godaddy. I have no idea how to put SSL certificate for my site running on 0.0.0.0:80 port. Its simple django webapp. Any one can help? Please. I have tried using but didn't work ''' pip install django-extensions pip install Werkzeug pip install pyOpenSSL ''' -
How to override save method of model to change filefield name?
I have a ModelForm in my django app which allows a user to upload a file and store it to aws storage s3. What I wish to do is rename the file from its original name to the name of the field timestamp. What I have tried so far is overriding the save method of the model. Here is my code: models.py from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone import time class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) timestamp = models.CharField(max_length=1000, default= time.time()) def __str__(self): return self.csv_file def save(self, *args, **kwargs): self.csv_file.name = self.timestamp + ".csv" super(CSVUpload, self).save(*args, **kwargs) forms.py from django import forms from .models import CSVUpload import time class CsvForm(forms.ModelForm): csv_file = forms.FileField(widget=forms.FileInput( attrs= { 'class': 'form-group', } )) timestamp = forms.CharField(initial = time.time()) class Meta: model = CSVUpload fields = ('csv_file', 'timestamp',) def save(self): csvfile = super(CsvForm, self).save() return csvfile my view: def uploadcsv(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): return redirect(about) else: form = CsvForm() return render(request, 'myapp/uploadcsv.html',{'form': form}) Despite that, when I upload the file it doesnt arrive on the bucket. I am not sure what is wrong but I suspect it lies on the save method. Could …