Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access objects of grandparent model associated with target model through ContentType GenericForeignKey?
I'm trying to filter objects of model based on associated grandparent model. They are associated with each other through an intermediary parent model. Parent model is associated with grandparent through ContentType GenericForeignKey. How can I access all objects of target model sharing same Grandparent. I tried to use GenericRelations on Grandparent but it did not work as it returns all the Parent Objects associated with that GrandParent Model. For that, I've to loop through querysets. Please check the code for details: class State(models.Model): name = models.CharField(max_length=25) population = models.PositiveIntegerField() class UnionTerritory(models.Model): name = models.CharField(max_length=25) population = models.PositiveIntegerField() class District(models.Model): name = models.CharField(max_length=25) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type','object_id') population = models.PositiveIntegerField() class Town(models.Model): name = models.CharField(max_length=25) district = models.ForeignKey(District,related_name='towns',on_delete=models.CASCADE) population = models.PositiveIntegerField() """Here, District can be connected to State or UnionTerritory but town will always be part of district.""" Now, if I select any State or UnionTerritory Object; I want to have access to all towns under it. I want to filter all Town instances who share same State or UnionTerritory. Towns can be connected to different districts which belong to same state or same UnionTerritory. How can I access UnionTerritory or State associated with Town and … -
Django Apps aren't loaded yet: How to import models
I have a Django project looking like > project > gui > __init__.py > models.py > views.py > ... > project __init__.py ... I am trying to sync the sqllite db in django with some info I periodically query from other sources. So in project.init.py I spawn a thread that periodically queries data. However, I am having trouble accessing my models from there and update the database, because when I try to import them into init.py from gui.models import GuiModel I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is there a trick to do that or a different way to create a separate thread? -
Django: Annotate aggregation of filtered related set
I'm looking for a way to annotate value of aggregated filtered related set. class Location(... ... class Ticket(... location = ForeignKey(Location...) date = ... price = ... I need to annotate maximal price of ticket in a daterange. So if I set only last 30 days, it returns me all Location objects and every object have 'max_price' annotation which equals to maximal price of the tickets from last 30 days. Tickets: <Ticket France 100 now-50days> <Ticket France 200 now-20days-> <Ticket France 300 now-20days> <Ticket Austria 200 now-10days> <Ticket Austria 50 now-10days> In this case, queryset returns: <Location France> + annotated 200 <Location Austria> + annotated 50 Is it possible to do it in one Query? -
Django - Form Does Not Save User Values
I currently have a form on the “myaccount.html” page of my web application. This form renders how I want however I cannot submit the form values for some reason to appear in the django admin. When a user hits “submit”, the page refreshes and the values stay in the input fields. I’ve tried many methods to solve this but no luck. I thought I had everything together but maybe I’m missing something somewhere? Is there anything I’m missing to resolve this issue? I’m new to Django so any help is gladly appreciated. Thanks! users/views.py from users.forms import CustomUserCreationForm from django.views.generic.edit import CreateView from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET, require_POST from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect from django.shortcuts import render, redirect from django.template import loader from django.urls import reverse_lazy from django.views import generic from django.views.generic import FormView from django.views.generic.edit import FormView from django.conf import settings from django import forms class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('home') template_name = 'signup.html' class change(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('myaccount') template_name = 'myaccount.html' def form_valid(self, form): form.instance.name = self.request.name form.instance.address = self.request.address form.instance.zip_code = self.request.zip_code form.instance.mobile_number = self.request.mobile_number form.save() return super(change, self).form_valid(form) users/models.py from … -
What is the purpose of setting a variable in self.send for Django Channels?
In Django Channels tutorial, you set a variable called 'text_message'. This is for the consumer to echo the message that it has received. def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(**text_data**=json.dumps({ 'message': message })) What is the use of 'text_message'? I have removed it so that it looks like this, and still successfully rendered the message in my HTML. def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(json.dumps({ 'message': message })) -
How to use JWT (JSON Web Tokens) with Django and Python for creating the REST API for signup and login
I've being trying to implement the JWT (JSON Web Tokens) in the Django project. But I was not able to achieve the same. Can you please help me with some tutorial or tips or links to study the same. I tried using the pyjwt in my project, but the token generated every time I hit the API was same for the same user email address and password. -
Download a file with selenium on Heroku
I am attempting to download a file from a link, parse the file, then save specific data to my heroku database. I have successfully set up my selenium chrome webdriver and I am able to log in. Normally, when I get the url, it begins downloading automatically. I have set up a new directory for the file to be saved to on heroku. It does not appear to be here or anywhere. I have tried different methods of setting the download directory, other methods of logging in to the website, and have functionally done it locally, but not in heroku production. # importing libraries from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time import datetime from datetime import timedelta import os import json import csv # temporary credentials to later be stored # as env vars user = "user" psw = "pasw" account = 'account' # this is the directory to download the file file_directory = os.path.abspath('files') # making this directory the default chrome web driver directory options = webdriver.ChromeOptions() prefs = { "download.default_directory": file_directory } options.add_experimental_option('prefs',prefs) # setting up web driver driver = webdriver.Chrome(chrome_options=options) # logging in to pinterest url_login … -
What is the easiest way to tag user-submitted questions with category tags on a Django-base site?
I am building a site in Django where users submit questions about a wide range of topics. When a question is submitted, I would like it to be tagged with the various categories to which it belongs so it can be grouped with related questions. For example, if someone asks "does breastfeeding increase the risk of cancer?", I want that question tagged with categories like "child care, breastfeeding, cancer, etc". I understand that categorizing content is a common issue and I am curious what the best options are. -
DRF: Built-in way to group fields in Serializer?
Is there a built-in way to group fields in Serializer/ModelSerializer or to modify JSON structure? There is a Location model: class Location(Model): name_en = ... name_fr = ... ... If I use ModelSerializer I get plain representation of the object fields like: {'name_en':'England','name_fr':'Angleterre'} I want to group some fields under "names" key so I get {'names':{'name_en':'England','name_fr':'Angleterre'}} I know I can create custom fields but I want to know if there is a more straightforward way. I tried Meta.fields = {'names':['name_en','name_fr']...} which doesn't work -
Can't understand WebAuthn API error from JavaScript
I am currently building out an AJAX registration endpoint for Django to allow for FIDO2 authentication (physical hardware key login). This is from following the example/documentation from Yubico's official fido2 python library. The only dependencies are cbor.js and js-cookie. Everything server-side is working for now, however, I keep getting this JavaScript error while invoking the navigator.credentials.create method TypeError: Failed to execute 'create' on 'CredentialsContainer': The provided value is not of type '(ArrayBuffer or ArrayBufferView)' The code: var csrftoken = Cookies.get('csrftoken'); fetch('/register/begin', { method: 'POST', headers: { 'X-CSRFToken': csrftoken } }).then(function(response) { if(response.ok) { return response.arrayBuffer(); } throw new Error('Error getting registration data!'); }).then(CBOR.decode).then(function(options) { console.log(options) //This line is not working return navigator.credentials.create(options); //More code... complete registration... I can't figure this out. Do you know whats wrong? Thanks! -
Django: How to correct created date/time
I've a model Order, that has a field created. It's intention is to show when the order took place (date and time speaking). I'm using this line to create the field in the model: current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') However, the reviewing it from admin panel, it shows It was created in the future: 10:52 pm of 27/12. When the time right now is: 6:11 pm. You can see these details in this screenshot: How can I make sure the correct time gets recorded in productio env? It'll be hosted using Google Cloud Products. Right know I'm in development env. View that creates the Order: @csrf_exempt def cart_charge(request): culqipy.public_key = settings.CULQI_PUBLISHABLE_KEY culqipy.secret_key = settings.CULQI_SECRET_KEY amount = request.POST.get('amount') currency_code = request.POST.get('currency_code') email = request.POST.get('email') source_id = request.POST.get('source_id') last_four = request.POST.get('last_four') dir_charge = {"amount": int(amount), "currency_code": currency_code, "email": email, "source_id": source_id} print(dir_charge) charge = culqipy.Charge.create(dir_charge) transaction_amount = int(charge['amount'])/100 #Necesario dividir entre 100 para obtener el monto real, #Esto debido a cómo Culqi recibe los datos de los pagos current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') shipping_address1 = request.user.profile.shipping_address1 shipping_address2 = request.user.profile.shipping_address2 shipping_department = request.user.profile.shipping_department shipping_province = request.user.profile.shipping_province shipping_district = request.user.profile.shipping_district order = Order.objects.create( token = charge['id'], total =transaction_amount, email= email, #Using email entered in Culqi module, … -
How to create likes and number of people viewing a particular blog in a blog app [on hold]
I have been working on a blog app that as at now, people can sign up, sign in, create posts, update posts, delete posts but i need logic for the users to like other peoples posts or show how many people have viewed a particular post. thanks -
Auto fill form field in html with data value and make it read only
I'm in process of creating a page where you can add a customer with some information regarding to them. I want to assign an unique id for each customer. I of course type in the basic information myself, but I also need a field in the form that has been populated with a generated random id, that has been checked in the database if it already exists. If it doesn't then fill it into the form, and if it does then generate a new one until a not used one is found. Models.py class Opretkunde(models.Model): Fornavn = models.CharField(max_length=30) Efternavn = models.CharField(max_length=50) Telefon = models.IntegerField() Adresse = models.CharField(max_length=50) Postnummer = models.IntegerField() IA = models.CharField(max_length=10) salgsperson = models.CharField(max_length=150, default="missing") The field IA is the field which should be automatically populated with the randomly generated value forms.py class Opret_kunde_form(ModelForm): class Meta: model = Opretkunde fields = ['Fornavn', 'Efternavn', 'Telefon', 'Adresse', 'Postnummer', 'IA'] views.py def index(request): if request.method == 'POST': form = Opret_kunde_form(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.salgsperson = request.user instance.save() return HttpResponseRedirect(reverse('createUser:createUser')) else: form = Opret_kunde_form() return render(request, 'createCustomer.html', {'form': form}) The function im using to generate a value looks like this def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return … -
Make django display non-jinja element while waiting for it to be completed
So here's what I'm trying to do. Let's say I have a really long function that takes some time to process. Eventually, the output needs to be displayed on a webpage. I'm using Python 3.6 and Django 2 framework. views.py from django.shortcuts import render import time def f(): time.sleep(5) return [5,6,7] def index(request): return render(request,'homepage/page.html', {'funcF':f}) So as you can see, I have a function that waits for 5 seconds to pass before returning an array of numbers. homepage/page.html <p> Hello there! </p> {% for r in funcF %} <p> {{r}} </p> {% endfor %} My goal is that I want Hello there! to be displayed and wait for 5 seconds to pass, then display the numbers in the array. In it's current state, the webpage instead takes 5 seconds to reload, and it displays both Hello there! and the numbers on the array all at once. Any bright ideas? -
How to pass a string with slashes from view to template?
Why does the below code gives me SyntaxError: unexpected token: ':' in the browser's console whenever test view is called? Is it because the JavaScripts sees the text after slashes in the URL as commented lines? How do I fix that? The view: def test(request): context = { 'url': 'https://www.google.com', } return render(request, 'explorer/test.html', context) The template test.html: <script> var url = {{ url }} console.log(url) </script> -
Getting seconds from a timer function to my view
I want to get the minutes and seconds from the timer in my template to my view. I already tried different approaches with an ajax.post request but it didnt really work how I wanted it to be. Here is my template: {% block content %} <!-- Timer function --> <script type="text/javascript"> var sec = 0; function pad ( val ) { return val > 9 ? val : "0" + val; } setInterval( function(){ $("#seconds").html(pad(++sec%60)); $("#minutes").html(pad(parseInt(sec/60,10))); }, 1000); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="minutes"></span>:<span id="seconds"></span> <form action="results" id=results method="POST"> <!-- after clicking on this button the minutes and seconds should also be sent as a POST request --> <div class="command"> <button type="submit" name="ctest_submit">Submit solution</button> </div> </form> {% endblock %} Now I want to get the minutes and seconds to my view as a POST request after clicking on the submit button. My idea was it to hide the time in a input like this: <input type="hidden" name="seconds" value="what should be in here???"> but I dont know what should be in value? -
Django inline has no ForeignKey
I have on error now. It's inline error, I trying to find the solution, and I'd tried for all day long but failed. I'm sorry about if this question is very easy and repeated. This is error, when I try to use inline it shows <class 'brick.admin.AdminRoomStateInline'>: (admin.E202) 'brick.RoomInfomation' has no ForeignKey to 'brick.RoomInfomation' models.py class RoomInfomation(models.Model): roomNum = models.PositiveSmallIntegerField(default=0, primary_key=True) roomFloor = models.PositiveSmallIntegerField(default=0) startPointX = models.PositiveSmallIntegerField(default=0) startPointY = models.PositiveSmallIntegerField(default=0) #referencing userInfo_RoomReservationFK = models.ForeignKey('UserInfo', null=True, blank=True) compInfo_RoomInfoFK = models.ForeignKey('CompanyInfomations', on_delete=models.CASCADE) companyRoomTypeInfo_RoomInfoFK = models.ForeignKey('CompanyRoomTypeInfomations', on_delete=models.CASCADE) def __unicode__(self): return '%s' % str(self.PositiveSmallIntegerField) class RoomState(models.Model): roomReservation_roomStateFK = models.ForeignKey('RoomInfomation') reservationBlock = models.BooleanField(default=False) reservated = models.BooleanField(default=False) reservatedDate = models.DateField(blank=True, null=True) reservationFirstDate = models.DateField(blank=True, null=True) reservationEndDate = models.DateField(blank=True, null=True) checkoutTime = models.DateField(blank=True, null=True) checkinTime = models.DateField(blank=True, null=True) admin.py class AdminRoomStateInline(admin.TabularInline): model = RoomInfomation extra = 8 # list_display = [ # 'roomReservation_roomStateFK', # 'reservationBlock', # 'reservated', # 'reservatedDate',#예약을 진행했던 날짜 # 'reservationFirstDate', # 'reservationEndDate', # 'checkoutTime', # 'checkinTime', # ] # inlines = [AdminRoomInfomationInline,] class AdminRoomInfomation(admin.ModelAdmin): fields = [ 'compInfo_RoomInfoFK', 'companyRoomTypeInfo_RoomInfoFK', 'userInfo_RoomReservationFK', 'startPointX', 'startPointY', 'roomNum', 'roomFloor' ] inlines = [AdminRoomStateInline,] #class RoomState(admin,ModelAdmin): #admin.site.register(RoomInfomation) #admin.site.register(RoomState, AdminRoomState) admin.site.register(UserInfo, AdminUserInfo) admin.site.register(RoomInfomation, AdminRoomInfomation) admin.site.register(RoomState) I double check that may not tried, for example, when I'd changed inline class AdminRoomState to … -
Reserved namespace issue with Django HttpResponseRedirect when calling from a defined view
Whenever I have set a redirect to another defined view, I am getting a namespace error. I have an app_name defined in urls.py, but I'm pretty sure that I am missing something obvious. Error: enter code here`Traceback (most recent call last): File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/areports/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/areports/reports/views.py", line 15, in entry_create_view return HttpResponseRedirect(reverse('reports:new_district_view')) File "/root/areports/venv/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'reports' is not a registered namespace views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import New_Event_Form, New_District_Form def entry_create_view(request): form = New_Event_Form(request.POST or None) if form.is_valid(): form.save() #form = New_Event_Form() context = { "form": form } return HttpResponseRedirect(reverse('reports:new_district_view')) else: print('Invalid') context = { 'form': form, } return render(request, "entry_create.html", context) def new_district_view(request): new_district = New_District_Form(request.POST) if new_district.is_valid(): new_district.save() new_district = New_District_Form() context = { "new_district": new_district } return render(request, "new_district.html", context) else: print('Invalid') context = { "new_district": new_district } return render(request, "new_district.html", context) def home_view(request): return render(request, "home.html", {}) urls.py from django.contrib import admin from django.urls import path … -
Django: Authentication credentials were not provided
I've pulled up a dozen similar SO posts on this topic, and have implemented their solutions to the best that I have understood them, yet they haven't worked for me. Why am I getting this error detail: "Authentication credentials were not provided." after using an AJAX Patch request to hit my Django Rest Framework endpoint? I appreciate your help! Some Details The header tells me "Status Code: 401 Unauthorized" I'm on my localHost development server (Postgres) I don't get this error with any other django forms or ajax (Get and Posts) requests running on other apps within this application. This is the first time I'm attempting a PATCH request Ultimately, Once this Ajax Patch request works I, simply want to add bookid to the ManyToManyField books field in the api.BookGroup model I've tried to follow the suggestions in similar posts which recommend adjusting the settings.py to allow the right authentication and permission methods. referring to the DRF documentation, I've also changed the permission classes to permission_classes = (IsAuthenticated,) which should allow a patch request if I'm logged in when making the request (and yes, I am definitely logged in) The form data in the ajax header shows that I am … -
Issue linking Jquery library to Django extended template
I am making a web app using Django (v2.1.4). In one of my models I have a "date" field to which I would like to add the "date picker" calander using jquery. I am having trouble properly linking the jQuery code to Django. Here are the relevant pieces of code (let me know if you need more) models.py class Detail(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='details') Location = models.CharField('Detail', max_length=255) date = models.DateField('event date', default=datetime.date.today) time = models.TimeField('event start time', default=now) compensation = models.DecimalField(max_digits=6, decimal_places=2, default=0) description = models.TextField(blank=True) def __str__(self): return self.text forms.py class DetailForm(forms.ModelForm): class Meta: model = Detail fields = ('Location', 'date', 'time', 'compensation', 'description', ) widgets = { 'date': forms.DateInput(attrs={'class': 'datepicker'}) } views.py @login_required @educator_required def detail_add(request, pk): study = get_object_or_404(Study, pk=pk, owner=request.user) if request.method == 'POST': form = DetailForm(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.study = study detail.save() messages.success(request, 'You may now add answers/options to the question.') return redirect('educators:detail_change', study.pk, detail.pk) else: form = DetailForm() return render(request, 'classroom/educators/detail_add_form.html', {'study': study, 'form': form}) template base.html {% load static %}<!doctype html> <html lang="en"> <head> ... <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”> <link rel=”stylesheet” href=”/resources/demos/style.css”> <script src=”https://code.jquery.com/jquery-1.12.4.js”></script> <script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”> </script> </head> ... {% block scripts %} {% endblock %} {% block scripts … -
Saving data on Django from a Vue Template
I managed to get vue to work inside a Django template and I wondering what would be the best way to save a variable with the result of the calculation (this is a simple web calculator made in view) in this.result.toString() to a database using Django. I Would like to save the results and the current date/time. Thank you! new Vue({ el: '#app', data: { // calculation:'15*98', // tempResult:'1470', calculation:'', tempResult:'', }, mounted() { let btns = document.querySelectorAll('.btn') for (btn of btns) { btn.addEventListener('click',function() { this.classList.add('animate') this.classList.add('resetappearanim') }) btn.addEventListener('animationend',function() { this.classList.remove('animate') }) } }, methods: { append(value) { this.calculation += value.toString() }, clear() { this.calculation = '' this.tempResult = '' }, getResult() { if(this.tempResult != ''){ this.calculation = this.tempResult //this.tempResult = '' } }, backspace() { this.calculation = this.calculation.slice(0,-1) } }, watch: { calculation() { if(this.calculation !== '' && !isNaN(this.calculation.slice(-1)) && this.calculation != this.result ){ this.tempResult = this.result.toString() } } }, computed: { result() { if(!isNaN(this.calculation.slice(-1))) return eval(this.calculation) else return eval(this.calculation.slice(0, -1)) }, fontSize() { // save result here ?? return this.fontSize = 50-(this.tempResult.length*1.25) } }, filters: { hugeNumber: (value) => { let parts = value.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " "); return parts.join("."); }, number: (value) => { return value.replaceAll('*','x') … -
geodjango - fit bounds of leaflet map for a single point
I've been trying to set a leaflet map center with a point coordinates passed as the context.geom variable in the template, I previously tried with the leaflet-django library, but I couldnt find a way to reset the settings configuration to recognize the .geom value I set up map with leaflet from scratch, no library, so far I got this views.py: def buscar_rol(request): if request.method == 'POST': srch = request.POST['srh'] if srch: match = D_Base_Roles.objects.filter(Q(rol__iexact=srch) | Q(dir__icontains=srch)) pto = match[0] js in Template: var map = L.map('pto_gis').setView([-23.64, -70.387],17); L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo(map); var pto_ubi = {{ pto.geom|geojsonfeature|safe }} var mrk = L.geoJson(pto_ubi).addTo(map); var loc_pto = pto_ubi.geometry.coordinates; mrkbounds = L.latLngBounds(loc_pto); but in the console it mrkbounds has only two points, and of the same coordinates, I tried also to pass the pto_ubi and loc_pro variables before setting the map to pass loc_pto as coordinate for the setView, : var pto_ubi = {{ pto.geom|geojsonfeature|safe }} var loc_pto = pto_ubi.geometry.coordinates; var map = L.map('pto_gis').setView(loc_pto,17); but i got a "TypeError: t is null" error is there a way to set up django-leaflet to override the zoom and center settings based on a context values from a search function?, or how could I make this … -
Django MPTT: Rebuild tree in migrations file
I already have a model in my project that I now want to use with django-mptt. This model already has some data in it. During migrations, you are asked to set default values for some of the fields django-mptt creates. As directed in the documentation, I set 0 as the one off default value. The documentation goes ahead and recommends running Model.objects.rebuild() after this is done to set the correct values in the fields. I would like to perform this operation via my migrations files. I do NOT want to run this via my django-shell as this is not a one off operation. My migration files is so: # -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-27 17:33 from __future__ import unicode_literals from django.db import migrations, models def migrate_mptt(apps, schema_editor): ProductCategory = apps.get_model("product", "ProductCategory") ProductCategory.objects.rebuild() class Migration(migrations.Migration): dependencies = [ ('product', '0016_auto_20181227_2303'), ] operations = [ migrations.RunPython(migrate_mptt), ] On migration, I receive the error AttributeError: 'Manager' object has no attribute 'rebuild'. The same command works perfectly in the shell, of course. I need to do this via migrations since I want this operation to be run automatically every time my project is deployed. -
get_or_create object created or found?
I want to use get_or_create in some view and I want to know if it is made or found? One of the lines looks like this: source,p = Source.objects.get_or_create(name="Website") -
collectstatic refers to wrong directory
I got a problem that I can't seem to to find the root cause for. When I run the 'collectstatic' command I get error file not found. I can see it tries to put files in wrong directory. First after running the command I get this question You have requested to collect static files at the destination location as specified in your settings: /var/www/projects/foobar/foobar/static Which is right. But I get this error: FileNotFoundError: [Errno 2] No such file or directory: '/var/www/projects/foobar/foobar/foobar/static' Thats one dir of 'foobar' to much. This is my settings for the production: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = '/var/www/projects/foobar/foobar/media' MEDIA_URL = '/media/' STATIC_ROOT = '/var/www/projects/foobar/foobar/static' STATIC_URL = '/static/' How come it adds an extra dir of 'foobar'?