Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to follow ForeignKey in unique_together constraint?
I have three Django Models: a Property Model, most importantly having a slug field; a Collection Model; and a PropertyCollectionRelationship Model. The last model models a ManyToMany relationship between the other two and is used as an explicit through of a ManyToManyField. from django.db import models class Property(models.Model): slug = models.SlugField() collections = models.ManyToManyField('Collection', blank=True, through='PropertyCollectionRelationship') # ... other unimportant stuff omitted ... class Collection(models.Model): pass # ... lots of stuff omitted ... class PropertyCollectionRelationship(models.Model): prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) I would like to add a uniqueness constraint which ensures that each collection has at most one property with any given slug. I tried to express this via a unique_together option in the Model Meta: class PropertyCollectionRelationship(models.Model): class Meta: unique_together = [['coll', 'prop__slug']] prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) This resulted in the following System Check Error: SystemCheckError: System check identified some issues: ERRORS: myapp.PropertyCollectionRelationship: (models.E012) 'unique_together' refers to the nonexistent field 'prop__slug'. How, if at all, can I achieve such a constraint? -
How do I query the database for all the points that are within a certain radius from a users location?
I am trying to get all the points from the database that are with a certain radius from the users location(e.g 10km). So basically I would like the user to input a location, which would then be converted to lat and lng using the google maps api and have the application search for and return all the stores in the database that are within a 10 km radius of the users location. I have tried Haversines formula but can't seem to get that to work since I do not have a strong understanding of how to filter search results from the database. Could anyone please explain to me how best to query the database for results within a 10km radius using Haversines formula? models.py: class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) views.py: def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 unit = 6371 # Distance unit (kms) radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude print(lat,lng,radius) limit = 1000 My views .py is returning to lng and … -
model() missing 1 required positional argument: 'request'
Error: model() missing 1 required positional argument: 'request' I want to do abstract api for all models in my app urls.py urlpatterns = [ path('api/object/', views.GeneralViewSet.as_view({'get': 'list'})) ] views.py class GeneralViewSet(viewsets.ModelViewSet): @property def model(self, request): return apps.get_model(app_label=self.request.data.get('app'), model_name=self.request.data.get('object')) def get_queryset(self, request): return self.model.objects.all() def get_serializer_class(self, request): GeneralSerializer.Meta.model = self.model return GeneralSerializer def post(self, request): queryset = self.model.objects.all() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I expect the list of my data of models for example for post api of { "app": "leads", "object": "Lead" } expect all data from Lead object -
How to display image from temp folder to template in Django
I have just started working on django(But I have worked on python for about a year). For my MFA application, I have created .png file(qr code) in my admin.py file and I have stored this png in /tmp/ dir. Now I need to show this image to template. The reason I have stored this file in temp dir becouse the image created is one time. SO I want to show this image view for once and delete after that. So anyone can help me to get me out from this? Thanks for advance qr_url = "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label, user, secret, label) url = pyqrcode.create(qr_url) random_file_path = datetime.datetime.now().strftime("%Y%m%d%H%M%S") url.png('/tmp/'+str(random_file_path)+'.png', scale=4)` This is how I created png I have tried by directly providing temp dir path. Also If I have to store the file in static then please help me for storing and deleting file in static folder`` -
What is exactly Meta in Django
i want know simply what is Meta class in django and what they do from django.db import models Class Author(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) class Meta: ordering=['last_name','first_name'] -
How to style certain tags when condition is met after extending 'base.html'?
I'd like to change the style of all 'select' in my DetailView, but only when certain condition is met (like {% if object.sth == 'sth' %} ). This html is extended from 'base.html' where I already have my css linked, and all 'select' styled. What would be the best approach? It seems I can not link new stylesheet while I'am already in (after extending base.html) -
Django rest fetch data from bridge model
I want to get all the user details and list of all the roles against the user details model My Models class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userdetail_user', default='111') cn = models.CharField(max_length=200) sn = models.CharField(max_length=200) u_id = models.CharField(max_length=200) display_name_cn = models.CharField(max_length=200) display_name_en = models.CharField(max_length=200) given_name = models.CharField(max_length=200) employee_number = models.CharField(max_length=200) email = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_login = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.given_name class Role(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) def __str__(self): return self.title class UserRole(models.Model): userdetail = models.ForeignKey(UserDetail, on_delete=models.CASCADE, related_name='userrole_userdetail') role = models.ForeignKey(Role, on_delete=models.CASCADE) approver = models.ForeignKey(UserDetail, on_delete=models.SET_NULL, null=True, related_name='userrole_userdetail_approver') created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) My Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class UserRoleSerializer(serializers.ModelSerializer): class Meta: model = UserRole fields = ('id', 'userdetail', 'role', 'approver', 'last_updated', 'status') depth = 1 def to_representation(self, instance): representation = super(UserRoleSerializer, self).to_representation(instance) representation['userdetail'] = UserDetailSerializer(instance.userdetail).data representation['role'] = RoleSerializer(instance.role).data representation['approver'] = UserDetailSerializer(instance.approver).data return representation class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('id', 'title', 'description', 'last_updated', 'status') class UserDetailSerializer(serializers.ModelSerializer): user = UserSerializer() roles = serializers.SerializerMethodField(read_only=True) class Meta: model = UserDetail fields = ('id', 'roles', 'user', 'cn', 'sn', … -
Deploying my Django website to Heroku with DEBUG=False doesn't work
When deploying django onto either localhost or heroku with DEBUG=False, it throws an error saying C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\ warnings.warn(u'No directory at: {}'.format(root)) [28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27 When DEBUG=True, it works fine. Why? And how do I stop and fix this? -
Use of `get` for a `select_for_update` query in order to reduce the number of rows getting locked
I would like to know if there is a good solution for this scenario. When a select_for_update is used in a query set, all matching results are locked until the particular block of code has not finished execution. This has become a little critical as simultaneous requests which could be served are being returned back by DatabaseErrors. Below is a sample query for which select_for_update has been implemented qs = Coupons.objects.select_for_update().filter(brand=brand).values('coupon').order_by('id') return qs[0] If we have 1000 coupons for a particular brand, then the entire 1000 rows are locked. I am unable to use get since we are returning the coupons on a FIFO basis and we would need to return coupons which were added first Is there any way I could use get, or minimize the number of rows being locked -
Aggregate related integer-field values in Django template
I have this model which is related to a Node model, class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name In the template when i query a list of the Node's objects i want to aggregate the value of the 'views_count' of each object. I have tried this in my template {% for tree in tree_result|slice:":14" %} {% for view in tree.related_views.all %} {{ view.views_count }} {% endfor %} {% endfor %} i have all the related count_view of the current tree but what i want to do is to aggregate the value of the related field and show it within the for loop of tree_result. Any suggestions please ? -
Django Blog Page not found (404) - No Post matches the given query
I'm coding a blog with Django,There was an error 404 when I click on address http://localhost:8000/blog/2019/7/28/prim-algorithm-path No Post matches the given query. Raised by: blog.views.blog_detail views.py def blog_detail(request,year,month,day,post): print(year,month,day,post) post = get_object_or_404(Post, slug=post, publish__year=year, publish__month=month,publish__day=day) return render(request,'post.html',locals()) blog/urls.py from django.urls import path from .views import index,blog_detail app_name = 'blog' urlpatterns = [ path('', index, name='index'), path('<int:year>/<int:month>/<int:day>/<slug:post>',blog_detail,name='post_detail'), ] mysite/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] what should I do -
Python dateparser fails when timezone is in middle
I'm trying to parse a date string using the following code: from dateutil.parser import parse datestring = 'Thu Jul 25 15:13:16 GMT+06:00 2019' d = parse(datestring) print (d) The parsed date is: datetime.datetime(2019, 7, 25, 15, 13, 16, tzinfo=tzoffset(None, -21600)) As you can see, instead of adding 6 hours to GMT, it actually subtracted 6 hours. What's wrong I'm doing here? Any help on how can I parse datestring in this format? -
User api request via app online - api server gets user or app IP adress?
I would like to publish an Django app on Vultr hosting. App (on user request) should connect an api on another server and return data to user. Api has requests limits by IP. When user connect api server via my app, api server will get user IP or my app server IP? If API server will get my app server ip my app will be banned after few request. How to avoid ban and send user ip to API server? Thank you for any help! -
How to save MultipleChoiceField to db
I want to create a settings page where a user can select multiple values of skills they have. It will have a main category and then subcategories. I need to save those into my database, so I can query them and show their selected skillset again. I know how to create the MultipleChoiceField but not how to save them to the database. How would I go on about that? Forms.py from django import forms class skills(forms.Form): jobs = [ ('Håndværker', ( ('Gulv', 'Gulv'), ('Væg', 'Væg'), ) ), ('Murer', ( ('Mur', 'Mur'), ('blabla', 'blabla'), ) ), ] job = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=jobs) Views.py from .forms import skills def index(request): if request.method == 'POST': form = skills(request.POST) if form.is_valid(): picked = form.cleaned_data.get('job') # do something with your results else: form = skills return render(request, 'settings/index.html', {"form":form}) It currently looks like this when the page loads which is good. Next step is just how I would save it to the database, so I can display this again with their previous chosen values. -
Error validating Django formset Modelform?
I am learning to implement Django formset using Modelform and I am getting this formset validation errors relating to my datefield. The error that I am getting is formset [{'from_date': ['Enter a valid date.'], 'to_date': ['Enter a valid date.']}] This is what I have tried so far.What could I be doing wrong ? models.py class WorkExperience(models.Model): company = models.ForeignKey(Company,on_delete=models.PROTECT) from_date = models.DateField() to_date = models.DateField() work = models.ForeignKey(Work,on_delete=models.PROTECT) date_last_modified = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True) forms.py class WorkExperienceForm(ModelForm): class Meta: model = WorkExperience fields=('from_date','to_date') def __init__(self, *args, **kwargs): super(WorkExperienceForm, self).__init__(*args, **kwargs) self.fields['name']=forms.CharField( label='Company Name', widget=forms.TextInput(attrs={ 'id': 'company_name', 'class': 'form-control', 'required':True }), ) self.fields['street_address'] = forms.CharField( label='Company Address', widget=forms.TextInput(attrs={ 'id': 'company_address', 'class': 'form-control', 'required': True }), ) self.fields['from_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['to_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['country'] = forms.ChoiceField(choices=Country.objects.all().values_list('id', 'name')) self.fields['country'].widget.attrs.update({'class': 'btn btn-secondary dropdown-toggle','required':True}) self.fields['project_name'] = forms.CharField( label='Project Name', widget=forms.TextInput(attrs={ 'id': 'project_name', 'class': 'form-control', 'required': True }), required=True, ) self.fields['project_details'] = forms.CharField( label='Project Details', widget=forms.Textarea(attrs={ 'id': 'project_details', 'class': 'form-control', 'required': True }), ) from django.forms import modelformset_factory WorkExperienceFormSet = modelformset_factory( WorkExperience, WorkExperienceForm, extra=1, ) views.py def post(self,request,*args,**kwargs): try: print('fromdate',request.POST['form-0-from_date']) formset = WorkExperienceFormSet(request.POST) print('formset',formset.errors) for form in formset: print('form',form.is_valid()) if … -
How to save a model-instance using serializers in django?
I would like to save a class instance in my database using serializers, provided by DRF. Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' here I try to save an instance: p = Person(Name = "Test") _srlz = PersonSerializer(data = p) The real case is little bit more complicated, but sanse the same. Unfortunately the data - _srlz.data is empty. So if I try to save data via _srlz.save() method then nothing change. Otherwise if I request an existed object p = Person.objects.filter(id = 1) _srlz = PersonSerializer(data = p) Then my _srlz.data will not be empty. How should I save this object if datasource is not JSON-object, but model-class instance?Should I first serialize it and then deserialize again? I already tried to save instance calling a .save() method, provided by model's default Manager, but I would like to separate my model and service methods so all database operations performed by serializers. Or is it OK in this case, because I deal not with pure JSON, but with model instance? But how can I then validate data? -
How to fix this datetime iso format error in django-python which is occuring since I upgraded my python to 3.7
This is the error that I am facing when I try to run migrate or runserver or any command. Please Help. "raise ValueError(f'Invalid isoformat string: {date_string!r}')" Code -
NoReverseMatch at / on the start of the server
It's giving me an error: NoReverseMatch at / targeting the base.html file (shown in the pic).But the base.html file looks fine to me. Base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Blog</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- Medium Style editor --> <script src="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One&display=swap" rel="stylesheet"> </head> <body class="loader"> <!-- Navbar --> <nav class="navbar custom-navbar techfont navbar-default"> <div class="container"> <ul class="nav navbar-nav"> <li><a class="navbar-brand bigbrand" href="{% url 'post_list' %}">My Blog</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="https://www.github.com">GitHub</a></li> <li><a href="https://www.linkedin.com">LinkedIn</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}" >New Post</a></li> <li> <a href="{% url 'post_draft_list' %}" >Drafts</a></li> <li> <a href="{% url 'logout' %}" >Logout</a></li> <li> <a href="#">Welcome: {{user.username}}</a> </li> {% else %} <li> <a href="{% url 'login' %}" class="nav navbar-right"> <span class="glyphicon glyphicon-user"></span> </a> </li> {% endif %} </ul> </div> </nav> <!-- COntent Block --> <div class="content container"> <div class="row"> <div class="col-md-8"> <div class="blog-posts"> {% block content %} {% endblock %} </div> </div> </div> </div> </body> </html> Post_detail.html {% extends 'blog/base.html' %} {% block content %} … -
how to get previous page url in django template?
i am using the django password reset but i want my template to behave differently when it come from password_rest_email and from password_reset_confirm urls.py from django.conf.urls import url,include #from django.urls import path from dappx import views from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetCompleteView,PasswordResetConfirmView # SET THE NAMESPACE! app_name = 'dappx' # Be careful setting the name to just /login use userlogin instead! urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), url(r'^', include('django.contrib.auth.urls')), url('password_reset/', PasswordResetView.as_view(), name='password_reset'), url('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), url('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] i need that template i.e(password_reset_confirm) to show email is send when it come from password_reset_email and show password reset successful if it come from password_reset_confirm password_reset_complete.html {% extends 'dappx/base.html' %} {% block title %}Check your Email{% endblock %} {% block body_block %} <div class="row no-gutters"> <div class="col-12 col-sm-6 col-md-8"></div> <div class="col-6 col-md-4"> <div class="jumbotron"> <h4>The password reset link has been sent to youre Email</h4> <br> <p>Check your email to reset the password. You can log in now on the <a href="{% url 'dappx:user_login' %}">log in page</a>.</p> <br> </div> </div> {% endblock %} -
Django Data to JsonResponse
I have this model that store all my data. This is my model.py: from django.db import models class Showing(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.CharField(max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.CharField(max_length=100) release_date = models.CharField(max_length=50, blank=True) def __str__(self): return "{}".format(self.movie_id) And I want to retrieve all my data and pass it to context and make a customize JsonResponse like this: "results": [ { "id": "1eb7758d-b950-4198-91b7-1b0ad0d81054", "movie": { "advisory_rating": "PG", "canonical_title": "ROGUE ONE: A STAR WARS STORY", "cast": [ "Felicity Jones", "Donnie Yen", "Mads Mikkelsen" ], "poster_portrait": "", "release_date": "", "synopsis": "Set shortly before the events of Star Wars (1977), Following the foundation of the Galactic Empire, the story will center on a wayward band of Rebel fighters which comes together to carry out a desperate mission: to steal the plans for the Death Star before it can be used to enforce the Emperor's rule. (Source: Disney Pictures)", } }, ] In my views.py I have this function to get all the data, and try just to retrive the movie_id from my model. def show_all_movies(request): movie = Showing.objects.all() context={'result':[{ 'id':movie.movie_id, 'movie': }]} But it gets me an error of 'QuerySet' object … -
how to send pre_save signal only when hit the save button for multiple form in one view (formset)
i trying to send signal only when the user hit the button save class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @receiver(pre_save , sender=ProductOrder) def create_order(sender, instance, **kwargs): Order.objects.create() if not instance.ordering: instance.ordering = Order.objects.all().order_by('-pk')[0] pre_save.connect(create_order,sender=ProductOrder) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) i want to make only one id from Order for all forms in the same view , while hit the button ? thanks for advice -
ModelForm add the primary ID for an entry in table based on last entry's primary ID
I am creating a signup system. I am using the django's default User's model to store user details, and I am passing its objects into a model named "Employee" where their department, manager and other info is stored. Here is what I have. models.py: from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') .... forms.py: from users.models import Employee from django.contrib.auth.models import User from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm class AddNewUserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class AddNewEmployeeForm(ModelForm): class Meta: model = Employee fields = {'department', 'manager', 'total_leaves'} add_new_user.html: <form method="POST"> {% csrf_token %} {{ form_user.as_p }} {{ form_emp.as_p }} <div class="text-center"> <button type="submit" class="btn btn-success">Submit</button> </div> </form> And this is how I'm processing the data in views.py: def post(self, request): form_user = AddNewUserForm(request.POST) form_emp = AddNewEmployeeForm(request.POST) if form_user.is_valid(): emp_info = form_emp.save(commit=False) emp_info.leaves_taken = 0 emp_info.user = form_user.save() emp_info.save() messages.success(request, "Success!") else: messages.error(request, form_user.errors) messages.error(request, form_emp.errors) return redirect("add_new_user") The problem is that when the post method is run, it tries to add entries into Employee table from the beginning; assuming there are no entries in it. But I have entries in that table and I get the following … -
How can i save some data in Django without adding it in the form?
I have a model which looks like this: class MyModel(models.Model): rate = models.CharField(max_length=100) amount = models.FloatField() userid = models.CharField(max_length=100) def save(self): # ALL the signature super(MyModel, self).save() And a form: class MyForm(forms.ModelForm): rate = forms.CharField() amount = forms.FloatField() class Meta: model = MyModel fields = ("rate", "amount") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send At the actual moment, my form is saving the fields rate and amount on my database, once the user uses the form. I would like to save on my DB the user who submitted the form, the date/time of when the form was saved and some other data that must not be submitted by the user, but saved 'automatically'. How can i do that in Django? -
How to generate a user password in plain SQL with Django + PostgreSQL
I want to insert from a Django into another Django database from other domain a proper password text in auth_user table. I have tried to generate a encrypt function but I don't know how Django generates a password from plain text into hashed password that is stored in database. postgres_insert_query = """ INSERT INTO auth_user (username, first_name, last_name, email, password) VALUES (%s,%s,%s,%s,%s) """ record_to_insert = (username, first_name, last_name, email, password) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() cursor.close() -
Django not serving static on digital ocean ubuntu 18.04
I have just successfully uploaded and run my project on digital ocean. It has been developed before production according to the coreyMS tutorials on youtube with the latest version of django 2.1.7. It has been deployed with this tutorial on ubuntu 18.04 on a digital ocean droplet. I cant make it serve any static files. The structure of my project is: newsite/myforum/ in here is the manage.py In the newsite/myforum/myforum/ is the settings.py and i have 3 apps users, forum and store that are all in folders in the newsite/myforum directory. The static folder according to the coreyms tutorial for the latest django version is supposed to be in my main app, therefore forum/static/forum. So the total path is newsite/myforum/forum/static/forum My settings are: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' In the nginx configuration i have specified the path, home/myuser/mydir/myenv/newsite/myforum maybe i should try: home/myuser/mydir/myenv/newsite/myforum/forum/static/forum or just: home/myuser/mydir/myenv/newsite/myforum/forum/static/ Or should i change my django settings and then run a collectstatic command. It took me a long time to get this far with the deployment and i dont want to run a stupid command and ruin it. Thank a lot for the help!!!!!!!!!!